工作中需要用到导出Excel功能,传统的方法比较复杂,不好修改。这里介绍一种封装好的工具类写法,只需要设置好实体类,用注解的方式写好对应的列名,再传入从数据库查出的数据集合就可以导出。
先来介绍代码,如果不想看的同学可以直接点击下载链接,里面有所有相关代码。https://download.youkuaiyun.com/download/shenjuntao520/18161800
首先pom引入jar包:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.13</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.13</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.13</version>
</dependency>
FileUtils.java:
/**
* 浏览器直接导出Excel文件
*
* @param filename 文件名称
* @param list 文件内容List
* @param clazz List中的对象类型
* @return ResponseBo
*/
public static ResponseBo createExcelByPOIKit(String filename, List<?> list, Class<?> clazz,HttpServletResponse response) {
if (list.isEmpty()) {
return ResponseBo.warn("导出数据为空!");
} else {
boolean operateSign = false;
String fileName = filename + ".xlsx";
operateSign = ExcelUtils.export(clazz, response)
// 设置每个sheet的最大记录数,默认为10000,可不设置
// .setMaxSheetRecords(10000)
.toExcel(list,"检测数据", null);
if (operateSign) {
return ResponseBo.ok(fileName);
} else {
return ResponseBo.error("导出Excel失败,请联系网站管理员!");
}
}
}
主要是调用这个方法,从浏览器直接导出Excel文件,filename是文件名,list是数据集合,clazz是集合中对象的类型,response是从Controller中传入的response。
ExcelUtils.java:
/**
* 用于浏览器导出
*
* @param clazz 实体Class对象
* @param response 原生HttpServletResponse对象
* @return ExcelUtils
*/
public static ExcelUtils export(Class<?> clazz, HttpServletResponse response) {
return new ExcelUtils(clazz, response);
}
export方法用来创建一个ExcelUtils类,其实就是个构造器。
public boolean toExcel(List<?> data,String sheetName, OutputStream out) {
return toExcel(data,sheetName, new ExportHandler() {
@Override
public CellStyle headCellStyle(SXSSFWorkbook wb) {
CellStyle cellStyle = wb.createCellStyle();
Font font = wb.createFont();
cellStyle.setFillForegroundColor((short) 12);
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);// 填充模式
cellStyle.setBorderTop(CellStyle.BORDER_THIN);// 上边框为细边框
cellStyle.setBorderRight(CellStyle.BORDER_THIN);// 右边框为细边框
cellStyle.setBorderBottom(CellStyle.BORDER_THIN);// 下边框为细边框
cellStyle.setBorderLeft(CellStyle.BORDER_THIN);// 左边框为细边框
cellStyle.setAlignment(CellStyle.ALIGN_LEFT);// 对齐
cellStyle.setFillForegroundColor(HSSFColor.GREEN.index);
cellStyle.setFillBackgroundColor(HSSFColor.GREEN.index);
font.setBoldweight(Font.BOLDWEIGHT_NORMAL);
// font.setFontHeightInPoints((short) 12);// 字体大小
font.setColor(HSSFColor.WHITE.index);
// 应用标题字体到标题样式