導出word文檔開發-freemarker
- 1.pom.xml
- 2.word模闆
-
- 3.代碼
- 4.FreeMarker基礎文法
- 5.建議
- 6.參考網站
1.pom.xml
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
- 這裡版本号自己控制(各版本差異自行百度)
- https://mvnrepository.com/artifact/org.freemarker/freemarker
2.word模闆
已WPS為例
- 打開需要開發導出的word文檔
- 另存為 選擇其他格式 選擇XML格式 儲存
- 在項目資源檔案夾建立 **.ftl 檔案
- 把另存的xml檔案内容貼近 **.ftl 檔案(或直接把xml扔進項目裡改名)
導出word文檔開發-freemarker1.pom.xml2.word模闆
//導出的xml裡對應模闆資訊
<w:r>
<w:rPr>
<w:rFonts w:hint="fareast"/>
<w:lang w:val="EN-US" w:fareast="ZH-CN"/>
</w:rPr>
<w:t>姓名:</w:t>
</w:r>
3.代碼
/**
* 使用FreeMarker通過模版生成word文檔,模版檔案需存放在/properties檔案夾下
* @param docData 模版中使用的資料
* @param ftlName 模版檔案的名稱,隻能是ftl類型檔案
* @param filePath 生成的doc檔案存放的位置
* @param fileName 生成的doc檔案的名稱(不含擴充名)
* @return
* @throws IOException
*/
public void createDoc(Map<String, Object> docData, String ftlName, String filePath, String fileName) throws IOException {
// FreeMarker模闆配置對象
Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
// 指定模版檔案目錄
configuration.setClassLoaderForTemplateLoading(this.getClass().getClassLoader(), "/properties");
// 指定模版字元集
configuration.setDefaultEncoding("UTF-8");
// 加載模闆檔案
Template tmplt = configuration.getTemplate(ftlName);
// 生成doc檔案的名稱
String docName = filePath + fileName + ".doc";
// 待doc檔案
File docFile = null;
try {
docFile = new File(docName);
Writer opWriter = new OutputStreamWriter(new FileOutputStream(docFile), "utf-8");
tmplt.process(docData, opWriter);
opWriter.flush();
opWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
4.FreeMarker基礎文法
//同EL表達式 ${name} // 這些基本都能解決了,如遇到不能解決的自行百度
1.if語句(判斷是否為空)
<#if target?? >
此處為if為true的内容
</#if>
2.list循環
<#list list as t>
${t.title}
</#list>
5.建議
//建議加上非空判斷 不建議直接使用 ${name} 來展示 不加判斷 值為空的話會報錯
<w:r>
<w:rPr>
<w:rFonts w:hint="fareast"/>
<w:lang w:val="EN-US" w:fareast="ZH-CN"/>
</w:rPr>
<w:t>姓名: <#if name?? && name != "">
${name}
<#else>
</#if>
</w:t>
</w:r>
6.參考網站
http://freemarker.foofun.cn/ 或直接百度