在开发程序中,系统内经常为了用户数据编写方便,同时大批量进行数据的整理而进行的Excel工具的导出导入的工作。
以下是在开发程序过程中,经过验证的导出Excel的核心代码逻辑,通过使用EasyExcel来快速达到导出的目的。
{
ServletOutputStream out = response.getOutputStream();
ExcelWriter excelWriter1 = EasyExcel.write(out).registerConverter(new LocalDateTimeConverter()).build();
//设置head信息
try {
WriteSheet writeSheet1 = EasyExcel.writerSheet(0, "页签的名字").head(heads).build();
excelWriter1.write(dataStr, writeSheet1);
response.setCharacterEncoding("utf-8");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName).getBytes(),
"ISO8859-1"));
out.flush();
}catch (Exception e) {
e.printStackTrace();
}finally {
if (excelWriter1 != null) {
excelWriter1.finish();
}
}
}
注意: 关于head的设置,工具类中提供了2种载入的方式,上述代码使用的是List<List<String>>的方式,同时它还支持class的方式。
相关表格样式的调整未在上述代码中指出。