EasyPOI 导出及各种问题总结
public class DealerNameExportDto implements Serializable {
contoller 层:调用入口
Service 层:处理数据,映射字段
// 设置excel的文件名称
String fileName = enName + "_" + System.currentTimeMillis();
MyExcelExportUtil.exportExcel(\'要导出的list数据\', pojoClass.class, \'文件头\', \'sheet名称\', response, \'文件名\');
Utils:
public class MyExcelExportUtil {
/**
* Excel文件导出,导出的文件名默认为:headTitle+当前系统时间
* @param listData 要导出的list数据
* @param pojoClass 定义excel属性信息
* @param headTitle Excel文件头信息
* @param sheetName Excel文件sheet名称
* @param response
*/
public static void exportExcel(Collection<?> listData, Class<?> pojoClass, String headTitle, String sheetName, HttpServletResponse response, String fileName) {
ExportParams params = new ExportParams(headTitle, sheetName);
params.setHeight((short) 8);
// 需要则添加样式
// params.setStyle(ExcelExportMyStylerImpl.class);
try {
Workbook workbook = ExcelExportUtil.exportExcel(params, pojoClass, listData);
// fileName = URLEncoder.encode(fileName, "UTF8");
response.setContentType("application/vnd.ms-excel;chartset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".xls\"");
ServletOutputStream out=response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
导出完成:
遇见的问题:
-
页面文件名出现乱码
fileName = URLEncoder.encode(fileName, "UTF8");
response.setContentType("application/vnd.ms-excel;chartset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename= "+ fileName + ".xls");修改完成:直接拼接fileName
response.setContentType("application/vnd.ms-excel;chartset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".xls\"");
-
当文件listData 要导出的list数据和pojoClass要实体类一致
/**
* Excel文件导出,导出的文件名默认为:headTitle+当前系统时间
* @param listData 要导出的list数据
* @param pojoClass 定义excel属性信息
* @param headTitle Excel文件头信息
* @param sheetName Excel文件sheet名称
* @param response
*/
ExportParams params = new ExportParams(headTitle, sheetName);
params.setHeight((short) 8);
// 需要则添加样式
// params.setStyle(ExcelExportMyStylerImpl.class);
Workbook workbook = ExcelExportUtil.exportExcel(params, pojoClass, listData);