使用freemaker模板生成word文件并填充数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lixu_csdn/article/details/88885300

1.java代码 

/**
     * 使用word模板生成文件(xxx.ftl)
     * @param request
     * @param documentOperation//模板信息实体类
     */
    private String generateFile(HttpServletRequest request, DocumentOperation documentOperation) {
        String filePath = null;

        Map<String, Object> params = new HashMap<String, Object>();

        Writer out = null;
        try {

            //取得要填充的相关信息数据
            params = fillDataUtils.fileDocumentData(dacasCaseNews);
            Configuration cfg = new Configuration();
            cfg.setDefaultEncoding("UTF-8");
            ServletContext servletContext = request.getSession().getServletContext();
            cfg.setServletContextForTemplateLoading(servletContext, "/templates");
            //获取模板
            Template tmp = cfg.getTemplate(documentOperation.getTemplateFile(), "UTF-8");

            String filename = documentOperation.getTemplateFileName() + DateUtils.dateToString(new Date(),"yyyyMMddHHmmss") +".doc";

            filePath = getGeneratePath(filename);//拼接文件写入的路径,判断不存在创建

            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"));
            tmp.process(params, out);


        } catch (Exception ex) {
            logger.error("", ex);
        }finally {
            if(out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return filePath;
    }

2.freemarker需要jar依赖可以网上找一下,以下是gradle的jar配置

3.将画好的word文件(xx.doc)修改后缀名会生成xml文件,或者改为.ftl文件,使用freemarker标签填充数据

 

猜你喜欢

转载自blog.csdn.net/lixu_csdn/article/details/88885300