1. 程式人生 > 其它 >spring boot整合freemarker實現根據word模版生成檔案並下載功能

spring boot整合freemarker實現根據word模版生成檔案並下載功能

技術標籤:javajavafreemarker

spring boot整合freemarker實現根據word模版生成檔案並下載功能

一、新增maven
    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.23</version>
    </dependency>
二、排除自動配置

啟動類上新增@EnableAutoConfiguration(exclude = { FreeMarkerAutoConfiguration.class })

註解。

三、製作模版

1.首先將word模版文件另存為xml格式文件。
2.再將xml模版文件字尾改為.ftl,例:test.xml改為test.ftl。
3.將檔案放在spring boot 專案目錄resources下的templates資料夾下。
在這裡插入圖片描述
4.寫入freemarker標籤到模版需要替換的位置。
在這裡插入圖片描述
如果有表格有動態資料,可以使用<#list>標籤。
在這裡插入圖片描述

四、程式碼實現
      @Value("${web.upload-path}")
      private String uploadPath;//生成的檔案存放的位置
     /**
     * exFileName:生成檔名稱
     * fileType:生成檔案型別,比如doc,xlsx
     * tempName:模版名稱
     * map:替換的資料
     */
public void contractExport(String exFileName, String fileType, String tempName, Map<String, Object> map, HttpServletResponse response) { Configuration configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); configuration.setTemplateLoader
(new ClassTemplateLoader(PurchaseContractServiceImpl.class, "/templates/")); //獲取需要匯出的資料 Map<String, Object> dataMap = map; Template t = null; try { String fileName = exFileName + "-" + System.currentTimeMillis() + "." + fileType; String tempPath = uploadPath; t = configuration.getTemplate(tempName); //要裝載的模板 File outFile = new File(tempPath + File.separator + fileName); if (!outFile.exists()) { outFile.createNewFile(); } Writer out = null; FileOutputStream fos = null; fos = new FileOutputStream(outFile); OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8"); out = new BufferedWriter(oWriter); t.process(dataMap, out); out.close(); fos.close(); download(outFile, response); } catch (Exception e) { e.printStackTrace(); } } /** * 下載生成的檔案並刪除臨時檔案 */ public void download(File file, HttpServletResponse response) { ServletOutputStream out = null; FileInputStream inputStream = null; try { String filename = file.getName(); response.setCharacterEncoding("utf-8"); response.setContentType("application/DOWLOAD"); response.setHeader("Content-Disposition", "attachment; filename=" + String.valueOf(URLEncoder.encode(filename, "UTF-8"))); out = response.getOutputStream(); inputStream = new FileInputStream(file); byte[] buffer = new byte[512]; int bytesToRead = -1; // 通過迴圈將讀入的Word檔案的內容輸出到瀏覽器中 while ((bytesToRead = inputStream.read(buffer)) != -1) { out.write(buffer, 0, bytesToRead); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != out) out.close(); if (null != inputStream) inputStream.close(); file.delete(); } catch (Exception e2) { e2.printStackTrace(); } } }
五、注意

1.替換資料map中key的值需要和模版總${xxxx}定義的值一致。
2.map中放的值不要為null,不然會報錯。當然也可以在模版使用freemarker標籤做null值的判斷,這裡就不說了,我也沒太研究,感覺沒必要。