当想要读写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>包裹起来。