文章目錄
- 與其他模版引擎對比
- 1.引入maven依賴包
- 2.新建Word文檔exportWprd.docx模版
- 3.編寫導出word接口代碼
- 4.導出成果
poi-tl是一個基于Apache POI的Word模板引擎,也是一個免費開源的Java類庫,你可以非常方便的加入到你的項目中,并且擁有著讓人喜悅的特性。中文網站
- 可以通過word模版引擎渲染文本、圖片、表格、列表數據
- 可以渲染條形圖(3D條形圖)、柱形圖(3D柱形圖)、面積圖(3D面積圖)、折線圖(3D折線圖)、雷達圖、餅圖(3D餅圖)、散點圖等圖表渲染
- 可以根據條件隱藏或者顯示某些文檔內容(包括文本、段落、圖片、表格、列表、圖表等)
- 可以根據集合循環某些文檔內容(包括文本、段落、圖片、表格、列表、圖表等)
- 支持設置書簽,文檔內錨點和超鏈接功能
- 模板即樣式,同時代碼也可以設置樣式
- 插件化設計,在文檔任何位置執行函數
與其他模版引擎對比
1.引入maven依賴包
(1)引入poi-tl包
<dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.12.2</version>
</dependency>
(2)因為poi-tl依賴于Apache POI5.2.2+,所以必須映入poi依賴包
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.2</version>
</dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>5.2.2</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>5.2.2</version><scope>compile</scope>
</dependency>
(3)繼續 引入poi-tl需要的commons-io與log4j-api依賴包(必須引入,否則會報錯,報錯如下)
<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.11.0</version>
</dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-api</artifactId><version>2.14.1</version>
</dependency>
不引入會導致報錯,報錯如下:
2.新建Word文檔exportWprd.docx模版
在靜態資源目錄下resources/static/templates新建exportWord.docx,編寫以下模版內容:
3.編寫導出word接口代碼
@GetMapping("/exportWord")public void exportWord(HttpServletResponse response) throws FileNotFoundException {//存放數據,也就是填充在word里面的值Map<String, Object> params = new HashMap<>();params.put("title","測試使用poi-tl模版導出word");params.put("ceshi","測試使用poi-tl模版導出word");params.put("name","張三");params.put("text","知之為知之不知為不知");//模板路徑// String templatePath = "E:\\demo\\word.docx";// 或模板在靜態資源的相對路徑File rootFile = new File((ResourceUtils.getURL("classpath:").getPath()));File templateFile = new File(rootFile, "/static/templates/exportWord.docx");//jar包獲取不到文件路徑`//URLDecoder.decode() 解決獲取中文名稱文件路徑亂碼String templatePath = URLDecoder.decode(templateFile.getPath());//生成文件名String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + System.currentTimeMillis();// 導出woldtry {// 導出Word文檔為文件XWPFTemplate template = XWPFTemplate.compile(templatePath).render(params);// 將導出的Word文件轉換為流response.setContentType("application/octet-stream");response.setHeader("Content-disposition","attachment;filename=\""+fileName+".docx"+"\"");// HttpServletResponse responseOutputStream out = response.getOutputStream();BufferedOutputStream bos = new BufferedOutputStream(out);template.write(bos);bos.flush();out.flush();// 最后不要忘記關閉這些流。PoitlIOUtils.closeQuietlyMulti(template, bos, out);} catch (Exception e) {System.out.println("導出Word文檔時出現異常:" + e.getMessage());}}