根据模板生成word

工具类
public class WordUtils {

    private static final Logger logger = LoggerFactory.getLogger(WordUtils.class);

    private final Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);

    public void createWord(String template, String docPath, Map<String, Object> dataMap) {
        // 加载文档模板FTL文件所存在的位置
        configuration.setClassForTemplateLoading(this.getClass(), "/template");
        configuration.setDefaultEncoding("UTF-8");
        Template t;
        try {
            t = configuration.getTemplate(template);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new ServiceException("io读写模板失败!");
        }
        //导出文件
        File outFile = new File(docPath);
        Writer out;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage(), e);
            throw new ServiceException("文件读取失败!");
        }
        try {
            if (t != null) {
                //将填充数据填入模板文件并输出到目标文件
                t.process(dataMap, out);
            }
            out.flush();
        } catch (TemplateException | IOException e) {
            logger.error(e.getMessage(), e);
            throw new ServiceException("word生成失败!");
        } finally {
            CloseUtil.closeQuietly(out);
        }
    }

}

ftl文件所在位置

如何生成ftl文件

  1. 将 word 中需要填充的数据用占位符${变量名}替换。
  2. 将该 word 另存为 .xml 的格式,检查看格式是否有误(主要看占位符$有没被分割开来)
  3. 将后缀.xml改成.ftl

ftl文件处理

 

生成ftl所需dataMap

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值