[alibaba/easyexcel]EasyExcel.write(response.getOutputStream())中午乱码

2024-05-10 358 views
7

版本:2.2.10 Controller: @ApiOperation(value = "统计分析:导出") @RequestMapping(value = "exportCountyResultList", method = RequestMethod.GET) public void exportCountyResultList(HttpServletRequest request,HttpServletResponse response) throws Exception { String authToken = (request.getParameter("token") != null) ? request.getParameter("token") : request.getHeader("Authorization"); String userId = BusinessJWTTokenUtil.getUsernameFromToken(authToken); String fileName = System.currentTimeMillis() + ".xlsx"; reportService.exportCountyResultList(response,userId, fileName); } Service: `public void exportCountyResultList(HttpServletResponse response, String userId, String fileName) throws CustomException, IOException { OutputStream outputStream = new FileOutputStream(filePath); response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding(StandardCharsets.UTF_8.toString()); // 处理中文乱码 String encode = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()); response.setHeader("Content-disposition", "attachment;filename=" + encode + ExcelTypeEnum.XLSX.getValue());

    EasyExcel.write(response.getOutputStream())
        .registerWriteHandler(new MyMergeStrategy(cellRangeAddressList))
        .registerWriteHandler(new SimpleColumnWidthStyleStrategy(20))
        .registerWriteHandler(writeColorHandler).head(headerList)
        .autoCloseStream(Boolean.TRUE).sheet("导出数据").doWrite(listO);

}`

Wps打不开,PostMan调用乱码

回答

3

image

5

在生成ExcelWriter对象的时候指定CSV格式就可以了:ExcelTypeEnum.CSV,具体原因与CSV文件的POM头有关。

ExcelWriter excelWriter = EasyExcel
                .write(response.getOutputStream(), XXX.class)
                .excelType(ExcelTypeEnum.CSV)
                .build()

问题记录:

  • 用file的方式就没问题
  • 把文件格式改成.xlsx,或者直接用Excel工具打开.csv文件,都没有问题。