最近遇到Springboot环境项目打成jar后下载Excle文件出现损坏问题,我是在网上找了这种方法解决的:
String fileName = "aaa.xlsx";
ClassPathResource cpr = new ClassPathResource("/download/" + fileName);
InputStream in = cpr.getInputStream();
XSSFWorkbook workbook = new XSSFWorkbook(in);
response.setContentType("application/binary;charset=ISO8859-1");
//防止中文乱码问题
String finalFileName = "";
String userAgent = request.getHeader("USER-AGENT");
if (userAgent.contains("Firefox")) {//火狐
finalFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
} else {//IE,google等其他浏览器
finalFileName = URLEncoder.encode(fileName, "UTF8");
}
response.setHeader("Content-disposition", "attachment; filename=" + finalFileName);
ServletOutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
要说明的是如果你是在Eclipse上或者IDEA上跑项目时下载就损坏,那你要看下pom中对resouces的权限配置,如果你在开发工具环境下下载没问题,在jar包环境有问题,可以用我以上代码试试,我的是这么解决的.