当想要读写word、excel,在网上查找资料大部分都是POI,但咱们要动态生成word文档时,首先要考虑的就是要保持word文档中的复杂样式,这时候咱们就应该考虑Freemarker的模板技术快速的实现这个功能。java
1、word读写实现思路:web
1.首先,将你须要的word文档用word2003打开(我只试过这个版本,可能别的版本的word可能也行,能够考虑试一下。可是wps再转换时就出问题了)。测试
2.将要动态替换的数据用${}替换,文件另存为,选择XMl格式,存为*.xml文件。spa
3.而后利用freemarker技术动态输出wor文档。excel
具体实现以下:xml
1).建立带有格式的word文档(我只用过word2003),将须要动态展现的数据用变量符替换。对象
注意:数据替换时纯手打或者总体复制,不能${}手打,中间变量复制,这样在生成.xml文档时会有问题。blog
2).将刚刚建立的word文档保存为.XMl格式。(可在文档中找一下变量符,看是不是一个总体。)utf-8
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);
}
}
2、excel读写的具体实现:
excel的具体实现yuword相似,只不过在生成模板中须要对模板进行调整
excel中若是要传入List,须要在模板中对要循环的部分用<#List list名称 as 对象></#List>包裹起来。