java导出word文档(Freemarker )

java导出word文档(Freemarker )

一、生成Word模板

生产word模版主要分为两步,一个是把word文档另存为xml文档,注意是另存为。然后把xml文档后缀改为ftl文档。在编辑word文档的时候,最好把需要填充或替换的位置,以一种特殊的标识符替代。

在这里插入图片描述

二、修改ftl模版

在文本编辑器里面打开ftl模版。然后搜索在word里填充的占位符。然后替换成后面能被替换的格式。比如,把Tb111,替换成${tb111}。这里可能原始的占位符发生了截断,比如本来是Tb111,但是在ftl模版里面成了Tb1~~<dafda<11。这时就要把中间的那些删掉。最后替换后的格式就是标准的可替换参数。

在这里插入图片描述

三、代码实现

添加依赖

<dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.28</version>
</dependency>
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class WordUtil {
    private static Logger LOGGER = LoggerFactory.getLogger(WordUtil.class);

    private static WordUtil service = null;

    private WordUtil() {
        super();
    }

    public static WordUtil getInstance() {
        if(service == null) {
            synchronized(WordUtil.class){
                if(service == null) {
                    service = new WordUtil();
                }
            }
        }
        return service;
    }



    /**
     *
     * @param templateFilePath  eg: /template/test/test.ftl
     * @param dataMap
     * @param exportFilePath  eg: /tmp/test/test123.doc
     * @param loadType  设置路径加载方式。1-绝对路径,2-项目相对路径
     * @return
     * @throws Exception
     */
    public File createDocFile(String templateFilePath, Map<String, Object> dataMap, String exportFilePath, int loadType) throws Exception {
        Template t = null;
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
        configuration.setDefaultEncoding("UTF-8");
        try {
            templateFilePath = pathReplace(templateFilePath);
            String ftlPath = templateFilePath.substring(0, templateFilePath.lastIndexOf("/"));
            if(loadType == 1) {
                configuration.setDirectoryForTemplateLoading(new File(ftlPath)); // FTL文件所存在的位置
            }else {
                configuration.setClassForTemplateLoading(this.getClass(), ftlPath);//以类加载的方式查找模版文件路径
            }


            String ftlFile = templateFilePath.substring(templateFilePath.lastIndexOf("/")+1);
            t = configuration.getTemplate(ftlFile); // 模板文件名

            File outFile = new File(exportFilePath);
            Writer out = null;

            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));

            t.process(dataMap, out);
        } catch (Exception e) {
            LOGGER.error("导出word文档出错", e);
            throw e;
        }

        return null;
    }

    /**
     *  把路径的\替换成/
     * @param path
     * @return
     */
    private String pathReplace(String path) {
        while(path != null && path.contains("\\")) {
            path = path.replace("\\", "/");
        }
        return path;
    }

    public static void main(String[] args) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        getData(dataMap);
        String templateFile = "D:\\test3.ftl";
        String exportFile = "D:\\luedf.doc";

        try {
            WordUtil.getInstance().createDocFile(templateFile, dataMap, exportFile, 1);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 添加的数据
     * @param dataMap
     */
    public static void getData(Map<String, Object> dataMap) {
        dataMap.put("Tb11", "10")}
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值