问题遇到的现象和发生背景
使用EasyExcel导出单文件多sheet页的excel文件,使用postman测试时,文件会直接导出到项目目录下,此时文件时正确的,但是当我用浏览器直接访问接口时,下载的文件是错误的,我在下面放图片。请看到的各位给指点一下。谢谢!
问题相关代码,请勿粘贴截图
@Override
@Transactional
public void WriteEmpeInfo(HttpServletResponse response) throws IOException {
String fileName = "EmpeInfo" + System.currentTimeMillis() + ".xlsx";
int count = 0;
ExcelWriter excelWriter = null;
excelWriter = EasyExcel.write(fileName).build();//创建文件
/*创建sheet页
* writerSheet:第几个sheet页,sheet页名
* head:继承了BaseRowModel的实体类 .class
* */
WriteSheet empeInfo = EasyExcel.writerSheet(0, "empeInfo").head(EmpeInfoExcel.class).build();
List<EmpeInfoExcel> empe = easyExcelMapper.selectEmpe();//查询数据库数据
excelWriter.write(empe, empeInfo);//把查到的数据写进sheet页
WriteSheet edauInfo = EasyExcel.writerSheet(1, "edauInfo").head(EdauInfoExcel.class).build();
List<EdauInfoExcel> edau = easyExcelMapper.selectEdau();
excelWriter.write(edau, edauInfo);
WriteSheet workInfo = EasyExcel.writerSheet(2, "workInfo").head(WorkInfoExcel.class).build();
List<WorkInfoExcel> work = easyExcelMapper.selectWork();
excelWriter.write(work, workInfo);
// response.setContentType("application/vnd.ms-excel");
// response.setCharacterEncoding("utf8");
// response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName,"UTF-8"));
File file = new File(fileName);
try {
if (!file.exists()) {
response.sendError(404, "File not found!");
return;
}
InputStream fis = new BufferedInputStream(new FileInputStream(fileName));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"), "iso8859-1"));
response.addHeader("Content-Length", "" + file.length());
//编码
response.setCharacterEncoding("UTF-8");
OutputStream out = new BufferedOutputStream(response.getOutputStream());
out.write(buffer);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
// 千万别忘记finish 会帮忙关闭流
excelWriter.finish();
}
运行结果及报错内容
浏览器直接访问的方式,下载的文件有问题,请看到的给位多多指教