1. 程式人生 > >java excel 寫入與下載實現 (解決亂碼問題)

java excel 寫入與下載實現 (解決亂碼問題)

情況描述:
Excel的預設編碼格式是 ANSI,但是 office 版本有很多
舊版本的excel無法開啟utf-8編碼的檔案,只能開啟ANSI編碼的檔案 (如office2007版本)
新版本的excel可以開啟utf-8編碼的檔案,也能開啟ANSI編碼的檔案 (如office2010版本)
因此,不能只是輸出一個檔案然後給它命名為 .csv/.xlx 這樣無法做到版本相容

解決方式:
生成一個excel然後再輸出,這樣就可以做到版本相容

程式碼:
1,2,3
4,5,6
7,8,9
檔案內容如上所示,然後寫入到excel並輸出

    /**
     *  將文字內容寫入Excel,然後下載該Excel
     * @param pathfile 待讀取的文字路徑
     * @param response 響應
     * @param fileName 生成的Excel檔名稱  (XXX.xls)
     */
    public void downLoadFile(String pathfile, HttpServletResponse response, String fileName) {
        try {
            //解決下載後的檔案中文名亂碼問題
            fileName = new String(fileName.getBytes("GBK"), "iso-8859-1");
        } catch (UnsupportedEncodingException e) {
            logger.error("", e);
            view.viewString(ParamUtils.errorParam("不支援iso-8859-1編碼格式"), response);
        }

        //宣告一個工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        //生成一個表格
        HSSFSheet sheet = workbook.createSheet(fileName);
        //向excel中寫入內容
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            fis = new FileInputStream(pathfile);
            isr = new InputStreamReader(fis,"utf-8");
            br = new BufferedReader(isr);

            String line;
            int i = 0;
            //按行讀取檔案中的內容,然後寫入Excel中(PIO也可以設定Excel的樣式)
            while((line = br.readLine()) != null){
                String str = line;
                String[] splits = str.split(",");
                HSSFRow nrow = sheet.createRow(i);
                for (int j = 0; j < splits.length; j++) {
                    HSSFCell nCell = nrow.createCell(j);
                    nCell.setCellValue(splits[j]);
                }
                i++;
            }
        } catch (FileNotFoundException e) {
            logger.error("指定的讀取檔案不存在\"", e);
        } catch (UnsupportedEncodingException e) {
            logger.error("文字內容不能轉成 utf-8", e);
        } catch (IOException e) {
            logger.error("寫入內容出錯", e);
        } finally {
            try {
                fis.close();
                isr.close();
                br.close();
            } catch (IOException e) {
                logger.error("讀取流關閉異常", e);
            }
        }

        //輸出excel
        response.reset();
        response.setCharacterEncoding("utf-8");
        // Content-disposition 告訴瀏覽器以下載的形式開啟
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        // application/ms-excel;charset=utf-8 告訴瀏覽器下載的檔案是excel
        response.setContentType("application/ms-excel");
        OutputStream out = null;
        try {
            out = new BufferedOutputStream(response.getOutputStream());
            workbook.write(out);
        } catch (IOException e) {
            logger.error("excel匯出有誤", e);
        } finally {
            try {
              out.close();
            } catch (IOException e) {
                logger.error("讀取內容有誤", e);
            }
        }
    }