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
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值