Apache POI:Excel读写库

时间:2022-06-02 16:02:29

1)Apache POI 简介

       Apache POI是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“简洁版的模糊实现“。基本功能如下:

  HSSF - 提供读写Microsoft Excel格式档案的功能。

  XSSF - 提供读写Microsoft Excel OOXML格式档案的功能。

  OOXML:Offic Open XML,微软以XML为基础并以ZIP格式压塑的电子文件规范,支持文件,表格,备忘录,幻灯片等格式。从Microsoft Offic 2007开始,OOXML已经成为Microsoft Offic默认的文件格式。

  HWPF - 提供读写Microsoft Word格式档案的功能。HSLF - 提供读写Microsoft PowerPoint格式档案的功能。HDGF - 提供读写Microsoft Visio格式档案的功能。

2) maven pom.xml配置

<dependency>  
    <groupId>org.apache.poi</groupId>  
    <artifactId>poi-ooxml</artifactId>  
    <version>3.15-beta2</version>  
</dependency> 

3)核心代码

/** 
 * 下载 
 * @param response 
 * @param list 
 * @param clazz 
 * @param templatePath 
 * @param templateName 
 * @throws Exception 
 */  
public static void download(HttpServletResponse response, List list, Class clazz, String templatePath, String templateName) throws Exception {  
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/M/d");  
    OutputStream os = response.getOutputStream();  
    try {  
        XSSFWorkbook workbook = ExcelUtil.getExportWorkBook(list, clazz, templatePath);  
        response.setHeader("Content-Disposition", "attachment; filename='" + templateName + "'");  
        response.setContentType("application/vnd.ms-excel");  
        workbook.write(os);  
    } catch (Exception e) {  
        e.printStackTrace();  
    } finally {  
        if (os != null) {  
            os.close();  
        }  
    }  
}  
/** 
 * 获取导出Excel工作薄 
 * 
 * @param list         数据源 
 * @param clazz        类 
 * @param templatePath 模板路径 
 * @return 
 * @throws Exception 
 */  
public static XSSFWorkbook getExportWorkBook(List list, Class clazz, String templatePath) throws Exception {  
    //获取导入模板  
    InputStream in = ExcelUtil.class.getResourceAsStream(templatePath);  
    XSSFWorkbook wb = new XSSFWorkbook(in);  
    XSSFSheet sheet = wb.getSheetAt(0);  
    //写入数据  
    writeDate(sheet, clazz, list);  
    return wb;  
} 
/** 
 * 写入数据 
 * 
 * @param sheet    表格 
 * @param clazz    类 
 * @param list     数据源 
 * @throws Exception 
 */  
public static void writeDate( XSSFSheet sheet, Class clazz, List list) throws Exception {  
    int propertyRowNum = 2;  
    XSSFRow propertyRow = sheet.getRow(propertyRowNum);//获取属性行  
    int columnCount = propertyRow.getLastCellNum();//获取属性行的列数  
    //循环赋值  
    for (int i = 0; i < list.size(); i++) {  
        Row dataRow = sheet.createRow(propertyRowNum + 1 + i);  
        //循环为每列赋值  
        for (int j = 0; j < columnCount; j++) {  
            String propertyString = propertyRow.getCell(j).getStringCellValue();  
            if (StringUtil.isEmpty(propertyString)) {  
                continue;  
            }  
            Method getMethod = getGetMethod(clazz, propertyString);//使用反射来获取方法和赋值  
            if (getMethod != null) {  
                Cell cell = dataRow.createCell(j);  
                CellStyle cellStyle = propertyRow.getCell(j).getCellStyle();  
                cell.setCellStyle(cellStyle);  
                setCell(list.get(i), getMethod, cell);  
            } else {  
                dataRow.createCell(j).setCellValue("");  
            }  
        }  
    }  
	if(propertyRowNum == sheet.getLastRowNum()){
		sheet.removeRow(propertyRow);//没有数据,清空属性行
	}else {
		sheet.shiftRows(propertyRowNum + 1, sheet.getLastRowNum(), -1);//有数据,清空属性行,全部数据行上移一行(该函数从起始行,到结束行,上移一行)
	}
}  
/** 
 * 根据关键词查找对应的get方法 
 * 
 * @param objectClass 
 * @param fieldName 
 * @return 
 */  
public static Method getGetMethod(Class objectClass, String fieldName) {  
    StringBuffer sb = new StringBuffer();  
    sb.append("get");  
    sb.append(fieldName.substring(0, 1).toUpperCase());  
    sb.append(fieldName.substring(1));  
    try {  
        return objectClass.getMethod(sb.toString());  
    } catch (Exception e) {  
    }  
    return null;  
}
 /**
     * 设置单元格的值
     *
     * @param object
     * @param method
     * @param cell
     * @return
     * @throws Exception
     */
    private static Cell setCell(Object object, Method method, Cell cell) throws Exception {
        String returnType = method.getReturnType().getName();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/M/d");
        switch (returnType) {
            case "java.util.Date": {
                java.util.Date cellValue = (java.util.Date) method.invoke(object);
                if (cellValue != null) {
                    cell.setCellValue(sdf.format(cellValue));
                }
            }
            break;
            case "java.lang.Float": {
                Float cellValue = (java.lang.Float) method.invoke(object);
                if (cellValue != null) {
                    cell.setCellValue(Double.valueOf(cellValue.toString()));
                }
            }
            break;
            case "java.lang.Double": {
                Double cellValue = (java.lang.Double) method.invoke(object);
                if (cellValue != null) {
                    cell.setCellValue(cellValue);
                }
            }
            break;
            case "java.lang.String": {
                String cellValue = (java.lang.String) method.invoke(object);
                if (StringUtil.isNotEmpty(cellValue)) {
                    cell.setCellValue(cellValue);
                }
            }
            case "java.lang.Integer":{
                Integer cellValue = (java.lang.Integer) method.invoke(object);
                if (cellValue != null) {
                    cell.setCellValue(cellValue);
                }
            }
            default:
                break;
        }
        return cell;
    }