poi(easypoi)导出excel(xls,xlsx)后,文件打开错误或乱码的解决方法(亲测) |
您所在的位置:网站首页 › word格式名无效 › poi(easypoi)导出excel(xls,xlsx)后,文件打开错误或乱码的解决方法(亲测) |
1.问题
今天我写一个导出excel数据的一个功能,一开始我使用XSSFWorkBook导出的是xlsx格式,结果下载文件后,打开报错: 然后我又切换成HssfWorkBook,导出xls格式,结果文件可以打开,但是内容却是乱码的。且他们的文件名均不是正常格式。 然后我就以为是编码问题,就开始各种搜索poi编码的问题,然后大部分都是说的给response对象添加content-Type之类的参数,但是我加了各种参数,都还是不对。 然后我想着可能不是编码问题,我就开始使用网页端,创建一个a标签去访问我的接口,结果发现文件正常了,也可以读取了。 原因不能使用postman等接口调用工具去请求这种需要下载文件的接口,这会有问题的。 解决方法前端创建一个a标签,然后href属性请求接口即可,注意,不要使用ajax,axios等异步请求去请求接口,这样是下载不了的 reponse最后再提供一个 reponse的设置吧 public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException { try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8")); workbook.write(response.getOutputStream()); } catch (Exception e) { throw new IOException(e.getMessage()); } } /** * Excel 类型枚举 */ enum ExcelTypeEnum { XLS("xls"), XLSX("xlsx"); private String value; ExcelTypeEnum(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |