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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值