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

    谢谢观赏

  • 相关阅读:
    oracle新建用户赋权限
    Linux配置tomcat自动启动
    java白皮书关键术语
    sql中exists和not exists的用法
    db2用户、权限相关命令
    面试问题
    能ping通,但是打不开网页
    kali linux的错误
    virtualbox display size
    Jetson tk1 安装 CUDA,ROS,OpenCV和kinect2以及刷机以及ssh远程控制
  • 原文地址:https://www.cnblogs.com/DidiLiu/p/13741884.html
Copyright © 2011-2022 走看看