java根据doc模板生成word文档
1, 打开word文档模板,在file目录中选择save as --> xml,将word模板保存成xml.
2, 由于这里使用了freemark框架做数据填充,故将xml改后缀为.ftl
3, 使用freemark占位符替换掉ftl模板中需要填充的内容
e.g ${overview.name!""} 替换模板中的name, !""的意思是如果overview.name为空默认设值为“”;
4,创建freemark configuration
public class ConfigurationSingleton {
private volatile static Configuration configuration = null;
private ConfigurationSingleton() {
}
public static Configuration getConfiguration() {
if (null == configuration) {
synchronized (ConfigurationSingleton.class) {
if (null == configuration) {
configuration = new Configuration(new Version("2.3.28"));
}
}
}
return configuration;
}
}
5, 封装数据,根据模板生成doc
Configuration configuration = ConfigurationSingleton.getConfiguration();
try {
configuration.setDirectoryForTemplateLoading(new File(“D:\template”));
Template template = configuration.getTemplate(“test_032521.ftl”);
File outDoc = new File(“D:\template\test_032521.doc”);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outDoc),“utf-8”));
Map<String, Object> dataMap = new HashMap<>();
ContactEntity ContactEntity = new ContactEntity();
ContactEntity .setContact_name(“test1”);
// ContactEntity .setCompanyName(“test”);
ContactEntity .setContact_phone("+86-18311218988");
ContactEntity .setContact_address_1(“555 Street Address”);
ContactEntity .setContact_address_2(“Suite 777”);
ContactEntity .setContact_city(“Chicago”);
ContactEntity .setContact_country(“USA”);
dataMap.put(“contact”, ContactEntity );
dataMap.put(“companyName”, “JP Mogan”);
dataMap.put(“overview”, new OverviewEntity());
template.process(dataMap, out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
生成完毕。