我出现的问题就是:excel导出文件名为中文会出现乱码
查找资料,主要说到两点
- 火狐浏览器使用的是Base64
- 火狐浏览器还有一个RFC标准
原来的代码:
//火狐导出,文件名出现乱码的问题解决
response.setHeader("Content-Disposition", "attachment;filename=" +
URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8"));
解决方案如下:
private 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"));
fileName = fileName + "." + ExcelTypeEnum.XLSX.getValue();
fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
fileName = new String(fileName.getBytes(), StandardCharsets.ISO_8859_1.name());
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + fileName);
workbook.write(response.getOutputStream());
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
测试结果:
测试成功解决乱码问题,尝试了火狐,谷歌win10自带浏览器,都没有出现乱码
火狐:
谷歌:
win10自带浏览器