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

 

謝謝觀賞


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM