Java導出Excel解決亂碼及導出文件打開不可讀需修復的問題

導入包,本來自己也不想用poi處理的,怎奈不知道爲什麼自己用流導出總是會報錯不可讀,所以還是簡單點吧:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency>

工具代碼:

public class FileUtil {

    public static void download(String filename, HttpServletResponse res) {
        String filePath = "./template/" + filename;
        try (OutputStream os = res.getOutputStream(); InputStream bis = new BufferedInputStream(new ClassPathResource(filePath).getInputStream())){
            // 設置信息給客戶端不解析
            String type = new MimetypesFileTypeMap().getContentType(filename);
            // 設置content-type,即告訴客戶端所發送的數據屬於什麼類型
            res.setContentType(type);
            // 設置編碼
            String name = URLEncoder.encode(filename, "UTF-8");

            // 設置擴展頭,當Content-Type 的類型爲要下載的類型時 , 這個信息頭會告訴瀏覽器這個文件的名字和類型。
            res.setHeader("Content-Disposition", "attachment;filename=" + name);
            XSSFWorkbook workbook = new XSSFWorkbook(bis);
            workbook.write(os);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}

重點是這句:XSSFWorkbook workbook = new XSSFWorkbook(bis);

文件所在位置:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章