easyExcel通过流的方式直接传给前端
记录easyExcel的一次实战
@Override
public void warehouserExcel(ResultDto resultDto, HttpServletResponse response) {
//获取模板
ClassPathResource classPathResource = new ClassPathResource("/excel/template/warehouse.xlsx");
//输入流
InputStream inputStream = null;
//输出流
ServletOutputStream outputStream = null;
//处理填充数据
DrugMasterEntity drugMasterEntity = getDate(resultDto);
List<DrugDetailEntity> drugDetailEntityList = drugMasterEntity.getDrugDetails();
ExcelWriter excelWriter = null;
try {
//输入流
inputStream = classPathResource.getInputStream();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("result", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
outputStream = response.getOutputStream();
excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
excelWriter.fill(drugDetailEntityList, fillConfig, writeSheet);
excelWriter.fill(drugMasterEntity, writeSheet);
outputStream.flush();
excelWriter.finish();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("导出入库单出错!");
} finally {
// 千万别忘记finish 会帮忙关闭流
if (excelWriter != null) {
excelWriter.finish();
}
//关闭流
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
借鉴了这位大佬https://blog.csdn.net/qq_53804496/article/details/126159181