SpringBoot Poi生成Excel文件时,下载的文件报错格式不正确需要修复
SpringBoot Poi生成Excel文件时,下载的文件用Excel打开报错格式不正确需要修复
使用spring boot框架,页面前端点击导出Excel,后端读取数据库数据使用Poi.jar生成Excel文件并下载到本地,下载的文件打开时,会提示后缀或者格式有错,需要修复。点击“是”修复时,提示文件损坏。本地windows环境调试时,没有上述错误。部署到Linux服务器时,出现上述错误。
原因
本地调试时,下载的文件都在localhost上完成,respons中没有设置“Content-Length”。从服务器下载时,文件流通过网络传输,没有设置“Content-Length”时,文件会损坏,因此需要设置“Content-Length”。
代码
前端js
let form = $('<form method="POST" name="excel-export-form" action="api/excelExport">');
$.each(data, function (k, v) {
form.append($('<input type="hidden" name="' + k + '" value="' + v + '">'));
});
$('body').append(form);
form.submit();
form.remove();
后端java
private static void buildExcelDocument(String fileName, Workbook wb, HttpServletResponse response) throws IOException {
DateFormat dateFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
String currentDateTime = dateFormatter.format(new Date());
String newFileName = fileName + currentDateTime + ".xlsx";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
wb.write(baos);
byte[] documentContent = baos.toByteArray();
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(newFileName, "utf-8"));
response.setContentLength(documentContent.length); // response响应头中设置传输文件长度
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
bos.write(documentContent);
wb.close();
baos.close();
bos.close();
}
jar包依赖
compile 'org.apache.poi:poi:4.1.2'
compile 'org.apache.poi:poi-ooxml:4.1.2'
compile 'xalan:xalan:2.7.2'
增加xalan,解决部署到服务器时报错(本地windows没有xalan也不报错):
Could not load the propery file 'output_xml.properties' for output method 'xml' (check CLASSPATH)