项目中最近用到这个东西,做下记录。

如下图,先准备好一个(office2003)word文档当做模板。文档中图片、姓名、性别和生日已经使用占位符代替,生成过程中将会根据实际情况进行替换。

使用freemarker模板生成word文档_另存为

然后将word文档另存为“Word XML文档”

使用freemarker模板生成word文档_导出文件_02

使用xml编辑器打开test.xml,将下图中的BASE64字符串替换为${image},后面程序中将使用这个替换图片。

使用freemarker模板生成word文档_Word_03

完成后,将test.xml重命名为test.ftl。

接下来,实现代码如下:

public class ExportDoc {

private Configuration configuration;
private String encoding;

public ExportDoc(String encoding) {
this.encoding = encoding;
configuration = new Configuration(Configuration.VERSION_2_3_22);
configuration.setDefaultEncoding(encoding);
configuration.setClassForTemplateLoading(this.getClass(), "/com/lichmama/test/templates");
}

public Template getTemplate(String name) throws Exception {
return configuration.getTemplate(name);
}

public String getImageStr(String image) throws IOException {
InputStream is = new FileInputStream(image);
BASE64Encoder encoder = new BASE64Encoder();
byte[] data = new byte[is.available()];
is.read(data); is.close();
return encoder.encode(data);
}

public Map<String, Object> getDataMap() {
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("name", "lichmama");
dataMap.put("gender", "男");
dataMap.put("birthday", "19**年**月**日");
try {
dataMap.put("image", getImageStr("D:\\头像.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
return dataMap;
}

public void exportDoc(String doc, String name) throws Exception {
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(doc), encoding));
getTemplate(name).process(getDataMap(), writer);
}

public static void main(String[] args) throws Exception {
ExportDoc maker = new ExportDoc("UTF-8");
maker.exportDoc("D:\\test.doc", "test.ftl");
}
}

生成的文档效果如下图:

使用freemarker模板生成word文档_Word_04