什么是 Word 模板替換
模板一般是具有固定格式的內(nèi)容,其中一部分需要替換。Word 模板通俗的講是以 Word 的形式制作模板,固定格式和內(nèi)容,然后將其中的一部分?jǐn)?shù)據(jù)替換掉。例如:在頒發(fā)證書時,證書大體內(nèi)容一致,只需要更換姓名以及獎項(xiàng)名稱。
如何實(shí)現(xiàn) Word 模板替換
Word 模板替換的方式有多種,對比之后最后選擇 HuTool 的工具類。HuTool 還有很多其他的工具類,可以訪問官網(wǎng)查看。
準(zhǔn)備模板
需要注意:模板內(nèi)容要求使用雙花括號{{}}
定義替換內(nèi)容。雙花括號中的標(biāo)記內(nèi)容可以隨意,這里我使用了數(shù)字作為標(biāo)記。
導(dǎo)入依賴
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
Java 核心代碼
public static void main(String[] args) throws IOException {
// 模板文件路徑
String registerTemplatePath = "C:\\Users\\Riu\\Desktop\\獎狀.docx";
// 輸出結(jié)果文件路徑
String putFileName = "C:\\Users\\Riu\\Desktop\\Tom-獎狀.docx";
// 替換內(nèi)容集合
Map<String, String> textMap = new LinkedHashMap<>();
textMap.put("0", "Tom");
textMap.put("1", "《活動名稱》");
textMap.put("2", "特等獎");
textMap.put("3", "2023");
textMap.put("4", "08");
textMap.put("5", "08");
// 調(diào)用工具類,registerTemplatePath 模板路徑,textMap 文字內(nèi)容
XWPFTemplate render = XWPFTemplate.compile(registerTemplatePath).render(textMap);
// 輸出文件到磁盤
render.writeToFile(putFileName);
}
轉(zhuǎn)換結(jié)果文章來源:http://www.zghlxwxcb.cn/news/detail-689701.html
根據(jù)個人測試,帶表格和帶圖片的均可以正常轉(zhuǎn)換,且格式正常。如有問題可以指正。文章來源地址http://www.zghlxwxcb.cn/news/detail-689701.html
到了這里,關(guān)于【技術(shù)】SpringBoot Word 模板替換的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!