Java Excel导出时文件名乱码
发现网上的这种方法不是很好用:new
String(formFileName.getBytes(
"UTF-8"
),
"ISO-8859-1"
)
现在使用的是:
java.net.URLEncoder.encode(fileName, "UTF-8")
前台再对文件名进行URLDecoder就可以了。
以下是代码:
@PostMapping(value = "/export") public void export(@RequestBody Map<String,String> map, HttpServletRequest request, HttpServletResponse response){ InputStream in = null; String fileNamePrefix = "fileNamePrefix_"; String rootpath = ""; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String nowDateTime = sdf.format(new Date()); String cycle = ""; String fileName = fileNamePrefix + nowDateTime + UUID.randomUUID().toString().substring(0, 8) + ".xlsx"; try { // 路径; rootpath = System.getProperty("user.dir")+"\\download\\"; //此方法导出数据到指定文件 exportSystemSumResult(systemMouldResult, rootpath, fileName); log.info("download file path:" + rootpath + fileName); response.reset();// 清空输出流 response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8")); // 定义输出类型 response.setContentType("application/vnd.ms-excel;charset=utf-8"); in = new FileInputStream(rootpath + fileName); response.setHeader("Content-Length", String.valueOf(in.available())); int n = 1024; byte[] buffer = new byte[n]; while (in.read(buffer, 0, n) != -1) { response.getOutputStream().write(buffer); } } catch(FileNotFoundException e){ log.info("无数据!"); }catch (IOException e) { log.error("导出失败,", e); } finally { if (in != null) { try { in.close(); } catch (IOException io) { log.error("关闭输出流失败", io); } } if (deleteFile(rootpath + fileName)) { log.info("delete file success,file path:" + rootpath + fileName); } else { log.error("delete file fail,file path:" + rootpath + fileName); } } }
谢谢观赏