2
private static void tableWrite(HttpServletResponse response, String fileName, Class mainTableClass,
List mainTableList, Class childTableClass, List childTableList) throws IOException {
HorizontalCellStyleStrategy strategy = setCellStyle();
ExcelWriter excelWriter = null;
OutputStream outputStream = setResponse(response, fileName);
try {
// 写入文件
excelWriter = EasyExcel.write(outputStream).build();
WriteSheet writeSheet = EasyExcel.writerSheet(SHEET_NAME).needHead(Boolean.FALSE).build();
// 指定表头需要使用哪个实例
WriteTable writeTable0 = EasyExcel.writerTable(TABLE_ONE).head(ImportNoteModel.class).needHead(Boolean.TRUE)
.registerWriteHandler(strategy).build();
WriteTable writeTable1 = EasyExcel.writerTable(TABLE_TWO).head(mainTableClass).needHead(Boolean.TRUE)
.registerWriteHandler(strategy).build();
WriteTable writeTable2 = EasyExcel.writerTable(TABLE_THREE).head(childTableClass).needHead(Boolean.TRUE)
.registerWriteHandler(strategy).build();
List nullList = Lists.newArrayList();
// 写入-导入须知,仅需要表头,不需要数据
excelWriter.write(nullList, writeSheet, writeTable0);
// NC模版要求主表与子表需要空一行
mainTableList.add(nullList);
// 写入-主表
excelWriter.write(mainTableList, writeSheet, writeTable1);
// 写入-子表
excelWriter.write(childTableList, writeSheet, writeTable2);
outputStream.flush();
} finally {
if (excelWriter != null) {
excelWriter.finish();
}
outputStream.close();
}
}
/**
* 设置response
*/
private static OutputStream setResponse(HttpServletResponse response, String fileName) throws IOException {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
return response.getOutputStream();
}