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

    谢谢观赏

  • 相关阅读:
    开启LOH压缩?
    搭建Hadoop2.6.4伪分布式
    EntityFramework CodeFirst SQLServer转Oracle踩坑笔记
    glob模式
    在Oracle中使用Entity Framework 6 CodeFirst
    IE9,10中console对象的bug
    ViewBag是如何实现的
    esbuild vs webpack
    企业微信公众号本地调试auto2.0
    vmware15.5的解锁mac系统插件
  • 原文地址:https://www.cnblogs.com/DidiLiu/p/13741884.html
Copyright © 2011-2022 走看看