freemaker用html的方式生成word文档

package com.xxx.framework.common.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.util.HtmlUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WordUtils {
    /**
     * html字符串生成word
     * @param content html字符串
     * @param filePath 生成文件的路径
     * @param fileName 文件名称
     */
    public static String createWord(String content, String filePath, String fileName) throws IOException {
        try {
            ClassPathResource resource = new ClassPathResource(filePath);
            //输出文件
            String dir = resource.getURI().getPath();
            String fileAbsolutePath = dir + File.separator + fileName + "_" + System.currentTimeMillis();
            if (!fileAbsolutePath.endsWith(".docx"))
                fileAbsolutePath += ".docx";
            File outFile = new File(fileAbsolutePath);
            //如果输出目标文件夹不存在,则创建
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }
            content = HtmlUtils.htmlUnescape(StringEscapeUtils.unescapeHtml(content));
            //格式化html
            byte[] by = content.getBytes();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(by);
            POIFSFileSystem poifsFileSystem = new POIFSFileSystem();
            DirectoryEntry directory = poifsFileSystem.getRoot();
            directory.createDocument("WordDocument", byteArrayInputStream);
            FileOutputStream fileOutputStream = new FileOutputStream(fileAbsolutePath);
            poifsFileSystem.writeFilesystem(fileOutputStream);
            byteArrayInputStream.close();
            fileOutputStream.close();
            return fileAbsolutePath;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 生成html字符串
     * @param dataMap 数据集
     * @param templateName 模板名称
     * @return
     */
    public static String createHtml(Map dataMap, String templatePath, String templateName) throws IOException, TemplateException {
        try {
            if (!templateName.endsWith(".ftl"))
                templateName += ".ftl";
            //创建配置实例 
            Configuration configuration = new Configuration();
            //设置编码
            configuration.setDefaultEncoding("UTF-8");
            configuration.setClassForTemplateLoading(WordUtils.class, templatePath);
            //获取模板 
            Template template = configuration.getTemplate(templateName);
            //将模板和数据模型合并生成文件
            StringWriter stringWriter = new StringWriter();
            //生成html
            template.process(dataMap, stringWriter);
            return stringWriter.toString();
        } catch (IOException ie) {
            throw ie;
        } catch (TemplateException te) {
            throw te;
        }
    }


    public static void main(String[] args) {
        Map dataMap = new HashMap();
        dataMap.put("name", "名称");

        List<Map> dataList = new ArrayList<>();
        Map dataItem1 = new HashMap();
        dataItem1.put("name", "第一行");
        dataItem1.put("one", "11");
        dataItem1.put("two", "12");
        dataItem1.put("three", "13");

        Map dataItem2 = new HashMap();
        dataItem2.put("name", "第二行");
        dataItem2.put("one", "21");
        dataItem2.put("two", "22");
        dataItem2.put("three", "23");

        Map dataItem3 = new HashMap();
        dataItem3.put("name", "第三行");
        dataItem3.put("one", "31");
        dataItem3.put("two", "32");
        dataItem3.put("three", "33");
        dataList.add(dataItem1);
        dataList.add(dataItem2);
        dataList.add(dataItem3);
        dataMap.put("dataList", dataList);

        String html = "";
        try {
            html = createHtml(dataMap, "/word-templates", "test.ftl");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (!"".equals(html))
                createWord(html, "/word-templates", "test.docx");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Word文档生成HTML模板主要通过将Word文档转换为HTML格式来实现。使用Freemarker作为模板引擎可以更方便地处理模板中的动态数据。 首先,我们需要将Word文档转换为HTML格式。可以使用一些开源的工具或者第三方库来完成这一步骤。例如,可以使用Apache POI来读取Word文档内容,并将其转换为HTML格式。将Word文档的段落、表格、图像等元素转换为相应的HTML标签,保留其基本格式。 然后,我们需要创建Freemarker模板,以定义生成HTML的结构和动态数据。可以使用Freemarker的语法来插入动态数据,如变量、条件判断、循环等。在模板中,我们可以将Word文档中提取的数据通过变量插入到相应的位置,实现动态生成HTML页面的效果。例如,可以将Word文档中的标题、正文、图片等内容与Freemarker模板中的对应部分关联起来。 最后,我们可以通过调用Freemarker模板引擎的相关方法,将模板与数据进行合并,生成最终的HTML文件。在生成过程中,动态数据会根据模板中的定义进行填充,从而生成具有动态内容的HTML页面。 需要注意的是,Word文档HTML页面的结构和样式是不同的,因此在转换和生成的过程中,需要进行相应的调整和处理。此外,还需注意保留Word文档中的一些特殊格式,如文本样式、超链接、表格边框等,确保转换后的HTML页面效果与原Word文档尽量一致。 总之,通过将Word文档转换为HTML格式,并使用Freemarker模板引擎来处理动态数据,可以实现Word文档生成HTML模板的需求。这样可以更加灵活地处理Word文档中的内容,并在生成HTML页面中实现相应的功能和效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值