freemarker 生成word

来源:互联网 发布:深入浅出node.js epub 编辑:程序博客网 时间:2024/05/16 17:33

java生成word的常用方法有三种,POI导出,itext,freemarker。本人用过后两种,对比而言itext适合生成简单格式word,如果生成多页word,则操作特变麻烦。如果你要生成的word内容有一个大体的模板,则更适合用freemarker。据说POI导出,如果生成多页格式复杂的word,操作也非常麻烦。

利用freemarker生成word前准备:

freemarker jar包,http://download.csdn.net/detail/xu281828044/7130817

foxe_CHS  xml编辑器用于处理word转换后的xml

生成word:

1.新建word,添加内容:


2.保存为xml


3.用foxe_CHS 打开保存后的xml文件,根据body 找到要填加内容的地方,加入${mark},"{}"中名称自定,在java操作中替换这部分内容。


4.保存修改后的xml文件,并将后缀修改为 .ftl,拷贝到项目中,同时加入 freemarker jar包。


5.java替换 word中内容:

package word;import freemarker.template.Configuration;import freemarker.template.Template;import java.io.*;import java.util.HashMap;import java.util.Map;public class CreateDoc {    private Configuration configuration = null;    public CreateDoc() {        configuration = new Configuration();        configuration.setDefaultEncoding("utf-8");    }    public void create() throws Exception {        Map<String, Object> map = new HashMap<String, Object>();        map.put("mark", "(大家好。测试成功!)");        configuration.setClassForTemplateLoading(this.getClass(), "/word/");        Template t = configuration.getTemplate("test.ftl");        File outFile = new File("D:/outFile.doc");        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));        t.process(map, out);    }    public static void main(String[] args) throws Exception {        new CreateDoc().create();    }}
结果:



0 0