下載resource下的excel文件

一、將excel文件放項目resources目錄下

二、打包的時候排除指定後綴文件,不然打包時會出現文件損壞的狀況
<configuration>
   <encoding>UTF-8</encoding>
   <nonFilteredFileExtensions>
   <nonFilteredFileExtension>xls</nonFilteredFileExtension>
   <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
   </nonFilteredFileExtensions>
</configuration>
三、resource配置
<resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.xlsx</include>
                </includes>
            </resource>
        </resources>
四、讀取resources下的xlsx文件
try {
            //獲取模板文件
            File sourceFile = ResourceUtils.getFile("classpath:bankNameTemplate.xlsx");
            //轉換爲文件流
            BufferedInputStream fs = new BufferedInputStream(new FileInputStream(sourceFile));             
            //指定默認下載名稱
            String fileName = "XXX.xlsx";
            //配置response的頭
            response.reset();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //循環從文件中讀出數據後寫出,完成下載
            byte[] b = new byte[1024];
            int len;
            while ((len = fs.read(b)) != -1) {
                response.getOutputStream().write(b, 0, len);
            }
            fs.close();
        } catch (Exception e) {
            logger.error("下載Excel模板異常", e);
        }
5.前端請求
  window.location.href = "/exportExcelTemplate";  
相關文章
相關標籤/搜索