springboot + freemarker 根据doc模板生成word文档

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();
}

生成完毕。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值