java下载csv乱码问题
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                java下载csv乱码问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                一.問題。
用EXCEL打開文件時,總是產生亂碼,但是用NOTEPAD++打開時,顯示正常。然后,在NOTEPADD++的“格式”工具欄中查了一下文件編碼,發現是“以UTF-8格式編碼”。
二.解決方法。
以CSV方式導出的文件中默認不含BOM信息,通過給將要輸出的內容設置BOM標識(以 EF BB BF 開頭的字節流)即可解決該問題。追加BOM標識 outputStream.write(0xef); outputStream.write(0xbb); outputStream.write(0xbf);
三.完整代碼。
@GetMapping(value = "/downloadFile",produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)public Object download(String id,HttpServletResponse response) {try {DataCleanManagement dataCleanManagement = dataCleanManagementService.getById(id);if (dataCleanManagement == null){return ResultVO.fail("文件不存在");}String path = config.filePath + File.separator + dataCleanManagement.getFilePath() + File.separator + dataCleanManagement.getResultFile();File file = new File(path);// 以流的形式下載文件。InputStream fis = new BufferedInputStream(new FileInputStream(path));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();// 清空responseresponse.reset();// 設置response的Header,給文件名進行utf-8編碼,不然下載的時候文件名亂碼不對response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode (file.getName(), "UTF-8" ));response.addHeader("Content-Length", "" + file.length());OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/vnd.ms-excel;charset=gb2312");outputStream.write(0xef);outputStream.write(0xbb);outputStream.write(0xbf);outputStream.write(buffer);outputStream.flush();outputStream.close();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();log.info(e.getLocalizedMessage(),e);}return null;}以上代碼請供參考,如有不當,請及時指出!
總結
以上是生活随笔為你收集整理的java下载csv乱码问题的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 前端测试 —— 技术选型及入门
 - 下一篇: 数据结构常见八大算法