Step1:
新建一个WordExport java项目,加入freemarker.jar.
Step2:
将要导出的Word模板转化为xml.
打开模板,单击‘文件’,单击’另存为‘
Step3:将xml模板中要插入数据的地方加上freemarker语句(转化前可以先在要插入的地方填写标示,通过查找标记来查找模板要插入的地方)(可用XMLSpy先将xml模板格式化)。
如果要插入只是一个字符串(如createDate),则在要插入处加上
<#if createDate??>${createDate!""}<#else> </#if>
如果要插入的是Map中的属性值(如clazz.school),则在要插入处加上
<#if clazz??>${clazz.school!""}<#else> </#if>
如果要插入是List,则在要插入处加上
<#if students??>
<#list students as student><!-- 将每一个元素命名为student-->
...
<w:t>${student.name!""}</w:t>
...
</#list>
</#if>
Step4:编写java类:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class Export {
public static void docOut() {
Configuration cfg = new Configuration();
cfg.setDefaultEncoding("utf-8");
try {
Template temp = cfg.getTemplate("test.xml");
temp.setEncoding("UTF-8");
//data为要导出的数据
Map<String,Object> data = new HashMap<String, Object>();
Map<String,Object> clazz = new HashMap<String,Object>();
clazz.put("school", "重理工");
clazz.put("clazzName", "软件一班");
clazz.put("clazzTea", "不便告知");
data.put("clazz", clazz);
List<Map<String, Object>> students = new ArrayList<Map<String, Object>>();
Map<String, Object> s1 = new HashMap<String, Object>();
s1.put("name", "bin");
s1.put("sex", "男");
s1.put("age",22);
students.add(s1);
HashMap<String, Object> s2 = new HashMap<String, Object>();
s2.put("name", "yu");
s2.put("sex", "女");
s2.put("age", 20);
students.add(s2);
data.put("students",students);
data.put("createDate", "2012年");
//一定要设置输出流的编码,否则会出错
Writer docout = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("test1.doc")),"UTF-8"));
docout.close();
//导出
temp.process(data, docout);
}
catch(TemplateException e){
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
docOut();
}
}
Step4:导出结果为:
下面是程序实例下载地址