POI-based import and export Excel package ExcelUtil streamlined

then
then

Note

Org.apache.poi for use herein is a simple package, for most excel import and export functions. Process might be used in reflection, as if the students have obsessive-compulsive disorder to the ultimate performance look like.

sequence

Since poi in itself is only a tool for office software packages like excel, excel at some conventional import and export, but also need to do a streamlined package, coupled to simplify the code.

First, the status

I have experienced several companies code package, there are the following general import and export situation.

1.1 Import

  1. Incoming file address, returns Sheet object, looping through the business code, do the corresponding conversion type, a service processing (two hundred years code frame)
  2. Address incoming file returns List <String, Object> object, and stronger external direct transfer
  3. Incoming file address, returns List <String, String> object, the external converts a String object to a corresponding type

Summary: If only the above choices, I am more inclined to the second, after all, the outer layer is very friendly

1.2 Export

  1. Traversing the sheet directly encapsulated in the logic code, the incoming file generating method (two hundred years code frame)
  2. List first loop through the object, is converted to List <Map <String, String >> object passed to a packaged tape fieldName good excel generated internal use as map.get () method of operation
  3. List fieldName target tape directly passed into the package good excel generation method, internally to convert the JSONObject Model object, and then use jsonObj.get () method of operation
  4. List first converted to the JSONArray, fieldName passed to bring the package good excel generation method, internally converted into the JSONObject Model object, and then use jsonObj.get () method of operation. (Using this approach, according to the analysis should be to perform jsonConfig.registerJsonValueProcessor (Date.class, new JsonDateValueProcessor ( "yyyy-MM-dd HH: mm: ss")); This line of code, possibly in order to solve the issue date type format )

Summary: If only the above choices, I am more inclined to third, third only traversed once, and without making external processing. But according to the fourth mode of view, the third model will still exist date format problem, the subsequent re-analysis of how we deal with.

Second, import

2.1 method definitions

/**
* excel导入
* @param keys		字段名称数组,如  ["id", "name", ... ]
* @param filePath	文件物理地址
* @return 
* @author yzChen
* @date 2016年12月18日 下午2:46:51
*/
public static List<Map<String, Object>> imp(String filePath, String[] keys)
    throws Exception {}
复制代码

Loop processing module 2.2

// 遍历该行所有列
for (short j = 0; j < cols; j++) {
    cell = row.getCell(j);
    if(null == cell) continue;	// 为空时,下一列
    
    // 根据poi返回的类型,做相应的get处理
    if(Cell.CELL_TYPE_STRING == cell.getCellType()) {
        value = cell.getStringCellValue();
    } else if(Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
        value = cell.getNumericCellValue();
        
        // 由于日期类型格式也被认为是数值型,此处判断是否是日期的格式,若时,则读取为日期类型
        if(cell.getCellStyle().getDataFormat() > 0)  {
            value = cell.getDateCellValue();
        }
    } else if(Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) {
        value = cell.getBooleanCellValue();
    } else if(Cell.CELL_TYPE_BLANK == cell.getCellType()) {
        value = cell.getDateCellValue();
    } else {
        throw new Exception("At row: %s, col: %s, can not discriminate type!");
    }
    
    map.put(keys[j], value);
}
复制代码

2.3

String filePath = "E:/order.xls";
String[] keys = new String[]{"id","brand"};

List<Map<String, Object>> impList;
try {
    impList = ExcelUtil.imp(filePath, keys);
    
    for (Map<String, Object> map : impList) {
        System.out.println(map.get("brand"));
    }
} catch (Exception e) {
    e.printStackTrace();
}
复制代码

2.4 Analysis

  1. Entrance only need to pass the file name, as well as key external can be read
  2. Internal processing, the values ​​for the type, date type, string type corresponding to the process has been done, the external direct transfer type corresponding to strong

Third, export

3.1 method definitions

/**
* excel导出
* @param fileNamePath	导出的文件名称
* @param sheetName	导出的sheet名称
* @param list		数据集合
* @param titles		第一行表头
* @param fieldNames	字段名称数组
* @return
* @throws Exception    
* @author yzChen
* @date 2017年5月6日 下午3:53:47
*/
public static <T> File export(String fileNamePath, String sheetName, 
    List<T> list, String[] titles, String[] fieldNames) throws Exception {}
复制代码

Loop processing module 3.2

// 遍历生成数据行,通过反射获取字段的get方法
for (int i = 0; i < list.size(); i++) {
    t = list.get(i);
    HSSFRow row = sheet.createRow(i+1);
    Class<? extends Object> clazz = t.getClass();
    for(int j = 0; j < fieldNames.length; j++){
        methodName = "get" + capitalize(fieldNames[j]);
        try {
            method = clazz.getDeclaredMethod(methodName);
        } catch (java.lang.NoSuchMethodException e) {	//	不存在该方法,查看父类是否存在。此处只支持一级父类,若想支持更多,建议使用while循环
            if(null != clazz.getSuperclass()) {
                method = clazz.getSuperclass().getDeclaredMethod(methodName);
            }
        }
        if(null == method) {
            throw new Exception(clazz.getName() + " don't have menthod --> " + methodName);
        }
        ret = null == method.invoke(t) ? null : method.invoke(t) + "";
        setCellGBKValue(row.createCell(j), ret + "");
    }
}
复制代码

3.3

String[] titles = new String[]{"Id", "Brand"};
String[] fieldNames = new String[]{"id", "brand"};
List<Order> expList = new ArrayList<Order>();
Order order = new Order();
order.setId(1L);
order.setBrand("第三方手动阀");
expList.add(order);
order = new Order();
order.setId(2L);
order.setBrand("scsdsad");
expList.add(order);

String fileNamePath = "E:/order.xls";
try {
    ExcelUtil.export(fileNamePath, "订单", expList, titles, fieldNames);
} catch (Exception e) {
    e.printStackTrace();
}
复制代码

3.4 summary

  1. The main entrance is the need to pass a List data collection, and field names fieldNames
  2. Internal processing, were obtained directly by reflection method get the return value into a string for export be strong
  3. For compatibility with some design inherits the parent class share fields, then add a layer of the parent class method of reading

Fourth, on the date of the type of export processing

1.1 Date fields to export the contents of a specified format

  1. Model-based recommendations, add an extension field, and packaging a get method, but contents of the fields of the original conversion, export, is passed to the fieldName extension field. As createTime, examples are as follows:
private Date createTime;
private String createTimeStr;	// 扩展字段

public Date getCreateTime() {
    return createTime;
}

public void setCreateTime(Date createTime) {
    this.createTime = createTime;
}

public String getCreateTimeStr() {
    createTimeStr = DateUtil.formatDatetime(this.createTime);
    return createTimeStr;
}

复制代码

My Blog

blog.guijianpan.com

Technology Exchange

Guess you like

Origin juejin.im/post/5d395752f265da1bd52312a3