zoukankan      html  css  js  c++  java
  • 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);
                }
            }
        }     
    View Code

    谢谢观赏

  • 相关阅读:
    算法基础~链表~求两个链表的交点(不考虑时间、空间复杂度)
    《人月神话》阅读笔记一
    html与css学习笔记
    新手教程
    课程信息管理
    关于文件动手动脑
    四则运算随机生成
    关于异常
    第四次动手动脑
    第三次动手动脑
  • 原文地址:https://www.cnblogs.com/DidiLiu/p/13741884.html
Copyright © 2011-2022 走看看