Java?poi-tl根據(jù)模板生成word文件的完整指南
基礎操作
本質(zhì)上是通過占位符進行內(nèi)容替換
本文章僅操作docx格式的文檔
- .doc (Word 97-2003): 使用OLE2格式,對應POI的 HWPF 組件
- .docx (Word 2007+): 使用OOXML格式,對應POI的 XWPF 組件
基礎操作_模板部分

將模板放入resources 資源目錄下,自定義文件夾中,例如:templet/word_template/demo_template.docx
代碼部分
maven
<!-- 用于生成word版報告 --> <dependency> <groupId>com.deepoove</groupId> <artifactId>poi-tl</artifactId> <version>1.12.1</version> </dependency>
處理過程
// 模板文件
String templateFilePath = "templet/word_template/demo_template.docx";
// 讀取模板文件
InputStream templateIn = getClass().getClassLoader().getResourceAsStream(templateFilePath);
// 插入文本數(shù)據(jù)
Map<String, Object> templateData = new HashMap<String, Object>();
templateData.put("str1", "替換成功");
// 生成模板文件
XWPFTemplate template = XWPFTemplate.compile(templateIn).render(templateData);
// 寫入數(shù)據(jù)并關閉流
template.writeAndClose(new FileOutputStream("D:/output.docx"));
templateIn.close();
此時,文件便下載到了 D:/output.docx 的位置。
若為Web
public void pgdExport(HttpServletResponse response) throws IOException {
// 模板文件
String templateFilePath = "templet/word_template/demo_template.docx";
// 讀取模板文件
InputStream templateIn = getClass().getClassLoader().getResourceAsStream(templateFilePath);
// 插入文本數(shù)據(jù)
Map<String, Object> templateData = new HashMap<String, Object>();
templateData.put("str1", "替換成功");
// 生成模板文件
XWPFTemplate template = XWPFTemplate.compile(templateIn).render(templateData);
ServletOutputStream outputStream = response.getOutputStream();
// 防止文件以及文件名亂碼
String fileName = "文件名.docx";
String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=utf-8''" + encodedFileName);
response.setCharacterEncoding("UTF-8");
// 寫入數(shù)據(jù)并關閉流
template.writeAndClose(outputStream);
templateIn.close();
}
// 前端js代碼 // 如果此接口需要被鑒權,那么需要后端同時從Params中獲取token,然后前端拼接token傳遞,否則此方法無法使用 // 需要注意跨域問題 window.location.href = '你的接口地址';
插入圖片
模板:占位符格式是{{@xxxx}}

代碼
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
templateData.put("img", Pictures.ofStream(in, PictureType.JPEG).size(300, 300).create());
參考文章:Java poi-tl根據(jù)模版生成word文件并插入文字、圖片、表格、圖表
到此這篇關于Java poi-tl根據(jù)模板生成word文件的完整指南的文章就介紹到這了,更多相關Java poi-tl模板生成word內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring多線程通過@Scheduled實現(xiàn)定時任務
這篇文章主要介紹了Spring多線程通過@Scheduled實現(xiàn)定時任務,@Scheduled?定時任務調(diào)度注解,是spring定時任務中最重要的,下文關于其具體介紹,需要的小伙伴可以參考一下2022-05-05
SpringBoot應用部署到外置Tomcat的實現(xiàn)
SpringBoot內(nèi)置tomcat使用很方便,本文主要介紹了SpringBoot應用部署到外置Tomcat的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2024-07-07
Spring?Boot?2.6.x整合Swagger啟動失敗報錯問題的完美解決辦法
這篇文章主要給大家介紹了關于Spring?Boot?2.6.x整合Swagger啟動失敗報錯問題的完美解決辦法,文中通過實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2022-03-03

