java导出word之freemarker导出
- - 企业架构 - ITeye博客 一,简单模板导出(不含图片, 不含表格循环). 1, 新建一个word文档, 输入如下类容:. 2, 将该word文件另存为xml格式(注意是另存为,不是直接改扩展名). 3, 将xml文件的扩展名直接改为ftl. 4, 用java代码完成导出(需要导入freemarker.jar).
@Test
public void exportSimpleWord() throws Exception{
// 要填充的数据, 注意map的key要和word中${xxx}的xxx一致
Map<String,String> dataMap = new HashMap<String,String>();
dataMap.put("username", "张三");
dataMap.put("sex", "男");
//Configuration用于读取ftl文件
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
/*以下是两种指定ftl文件所在目录路径的方式, 注意这两种方式都是
* 指定ftl文件所在目录的路径,而不是ftl文件的路径
*/
//指定路径的第一种方式(根据某个类的相对路径指定)
//configuration.setClassForTemplateLoading(this.getClass(),"");
//指定路径的第二种方式,我的路径是C:/a.ftl
configuration.setDirectoryForTemplateLoading(new File("C:/"));
// 输出文档路径及名称
File outFile = new File("D:/test.doc");
//以utf-8的编码读取ftl文件
Template t = configuration.getTemplate("a.ftl","utf-8");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
t.process(dataMap, out);
out.close();
}
Map<String,String> dataMap = new HashMap<String,String>();
dataMap.put("imgStr", getImageStr());
//....其余省略
public String getImageStr() {
String imgFile = "d:/aa.png";
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}