當想要讀寫word、excel,在網上查找資料大部分都是POI,但我們要動態生成word文檔時,首先要考慮的就是要保持word文檔中的復雜樣式,這時候我們就應該考慮Freemarker的模板技術快速的實現這個功能。
一、word讀寫實現思路:
1.首先,將你需要的word文檔用word2003打開(我只試過這個版本,可能別的版本的word可能也行,可以考慮試一下。但是wps再轉換時就出問題了)。
2.將要動態替換的數據用${}替換,文件另存為,選擇XMl格式,存為*.xml文件。
3.然后利用freemarker技術動態輸出wor文檔。
具體實現如下:
1).創建帶有格式的word文檔(我只用過word2003),將需要動態展示的數據用變量符替換。
注意:數據替換時純手打或者整體復制,不能${}手打,中間變量復制,這樣在生成.xml文檔時會有問題。
2).將剛剛創建的word文檔保存為.XMl格式。(可在文檔中找一下變量符,看是否是一個整體。)
3).從freemarker官網下載最新的jar包,將其拷貝到自己的開發項目中
4).新建freemarkerUtil類,實現可用freemarker技術根據xml模板生成word的方法。
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.*;
import java.util.Map;
public class Freemarker {
Configuration configuration = null;
public Freemarker() {
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
}
public void createDoc(Map dataMap,File readFile,File outFile,String fileName) {
// 設置模本裝置方法和路徑
Template t = null;
try {
configuration.setDirectoryForTemplateLoading(readFile);
t = configuration.getTemplate(fileName); // 裝載.xml模板
} catch (IOException e) {
e.printStackTrace();
}
// 輸出文檔路徑及名稱
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFile),"utf-8"));
} catch (Exception e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
5).建立測試類,試驗是否能夠成功。
下面是源碼:
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.TemplateException;
public class FreeMarkerTest {
public static void main(String[] args) throws IOException, TemplateException {
Freemarker tf = new Freemarker();
String filePath = "D:\\project\\src\\web_src\\test\\template";
Map dataMap = new HashMap();
dataMap.put("tansferMemberName", "轉讓方");
dataMap.put("prodName", "產品1");
dataMap.put("prodCode", "prodCodeOne");
File readFile = new File(filePath);
File outFile = new File("D:/outFileDoc.doc");
String fileName = "word.xml";
tf.createDoc(dataMap, readFile, outFile, fileName);
}
}
二、excel讀寫的具體實現:
excel的具體實現yuword類似,只不過在生成模板中需要對模板進行調整
excel中如果要傳入List,需要在模板中對要循環的部分用<#List list名稱 as 對象></#List>包裹起來。