前言
有一個(gè)需求就是給定一個(gè)正確格式的 Word 文檔模板,要求通過動(dòng)態(tài)賦值方式,寫入數(shù)據(jù)并新生成 該模板格式的 Word 文檔。這很明顯使用 Java+freemarker 方式來實(shí)現(xiàn)頗為簡(jiǎn)單。
一、導(dǎo)入依賴
<!-- freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
二、存入模板
(1)準(zhǔn)備好一個(gè)正確格式的 Word 文檔(測(cè)試文檔 - 原版.docx)
(2)將其另存為xml文件(測(cè)試文檔?- 原版.xml)
(3)隨便找個(gè)在線 XML 格式化工具處理一下(測(cè)試文檔 - 原版【格式化】.xml)
(4)將該 xml 模板存放在 /src/main/resources/templates/freemaker/ 目錄中
(5)使用 EL 表達(dá)式對(duì)模板進(jìn)行賦值
三、Xml 轉(zhuǎn) Doc/Docx
(1)/src/main/java/org/example/test/Main.java文章來源:http://www.zghlxwxcb.cn/news/detail-706732.html
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class ConvertXmlToDoc {
/**
* Xml 轉(zhuǎn) Doc
*/
private static void tranform() {
Map<String, Object> map = new HashMap<>();
map.put("question_1","一加一等于幾");
map.put("answer_1","二");
map.put("question_2","什么叫余弦定理");
map.put("answer_2","余弦定理,歐氏平面幾何學(xué)基本定理。余弦定理是描述三角形中三邊長(zhǎng)度與一個(gè)角的余弦值關(guān)系的數(shù)學(xué)定理,是勾股定理在一般三角形情形下的推廣,勾股定理是余弦定理的特例。");
try {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_20);
configuration.setClassForTemplateLoading(ConvertXmlToDoc.class, "/templates/freemaker"); // 指定 xml 模板存放的位置,即:項(xiàng)目目錄/src/main/resources/templates/freemaker
// 獲取 xml 模板
Template template = configuration.getTemplate("測(cè)試文檔 - 原版【格式化】.xml");
// 輸出 doc/docx 文件
File outFile = new File("D:/" + "測(cè)試文檔 - 修訂版【重制版】" + ".docx");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
template.process(map, out);
System.out.println("轉(zhuǎn)換成功");
} catch (Exception e) {
System.out.println("轉(zhuǎn)換失敗");
e.printStackTrace();
}
}
public static void main(String[] args) {
tranform();
}
}
四、運(yùn)行效果
文章來源地址http://www.zghlxwxcb.cn/news/detail-706732.html
到了這里,關(guān)于基于Java+freemarker實(shí)現(xiàn)動(dòng)態(tài)賦值以及生成Word文檔的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!