admin管理员组

文章数量:1633328

1、使用freemarker生成word

freemarker生成word的方法网上有很多,比较简单,基本上都差不多

所需工具

freemarker

<dependency>
	<groupId>org.freemarker</groupId>
	<artifactId>freemarker</artifactId>
	<version>2.3.31</version>
</dependency>
准备模板

准备一个word文档,为了防止有的用户还在使用非常老的word版本,这里选择生成2003版的 .doc 文件(也可以根据需求使用 .docx 文件),注意先将文档中要替换的内容写成 ${} 的形式,方便使用freemarker进行内容替换(文档中加入了一张图片,是为了演示怎么在生成word文档时添加图片)

另存为xml文件

生成的xml文件内容没有格式化,不方便查看,可以先将文件内容格式化(比如使用idea),然后找个文档编辑器,nodepad++,ueditor等都可以,直接在idea里编辑也可以,搜索一下占位符 $ 的位置,有的占位符可能会出现位置错乱,比如可能出现以下情况,这种情况就需要手动处理一下

这里特殊说明一下图片,图片是以base64编码的形式存在的,生成xml后直接将对应的base64字符串替换成占位符即可,比如 ${photo}

准备好模板文件后,将模板后缀改成 .ftl 放到工程resource目录下或文件系统目录下即可

代码

FreeMarkerForDocUtil.java

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * word文档生成工具类
 *
 * @author blank
 */
public class FreeMarkerForDocUtil{
   

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

    /**
     * 生成word文档,并保存成文件
     * @param templatePath 文档模板所在的文件夹
     * @param templateFileName 文档模板的名称
     * @param dataMap 模板中需要替换的数据
     * @param targetFilePath 目标文件路径
     * @param targetFileName 目标文件名
     * @return File
     * @throws IOException
     * @throws TemplateException
     */
    public static File generateWord(String templatePath, String templateFileName, Map<String,Object> dataMap,String targetFilePath,String targetFileName) throws IOException, TemplateException {
   
        byte[] wordBytes = createWord(templatePath, templateFileName, dataMap);
        File filePath = new File(targetFilePath);
        if(filePath.isDirectory() && !filePath.exists()){
   
            filePath.mkdirs();
        }
        File file = new File(targetFilePath+File.separator+targetFileName);
        FileOutputStream fOut = new FileOutputStream(file);
        fOut.write(wordBytes);
        fOut.close();
        return file;
    }

    /**
     * 生成word文档,并返回byte数组
     * @param templatePath 文档模板所在的文件夹
     * @param templateFileName 文档模板的名称
     * @param dataMap 模板中需要替换的数据
     * @return 二进制数组
     * @throws IOException
     * @throws TemplateException
     */
    public static byte[] generateWord(String templatePath, String templateFileName, Map<String,Object> dataMap) throws IOException, TemplateException {
   
        byte[] wordBytes = createWord(templatePath, templateFileName, dataMap);
        return wordBytes;
    }

    /**
     * 生成word文档
     * @param templatePath 文档模板所在的文件夹
     * @param templateFileName 文档模板的名称
     * @param dataMap 模板中需要替换的数据
     * @return 二进制数组
     */
    private static byte[] createWord(String templatePath, String templateFileName, Map<String,Object> dataMap) throws IOException, TemplateException {
   
        Configuration configuration = getConfiguration(templatePath);
        Template template = configuration.getTemplate(templateFileName);

        for(Map.Entry<String,Object> entry:dataMap.entrySet()){
   
            String value = entry.getValue().toString();
            // 处理转义字符
            value = transformForDoc(value);
            entry.setValue(value);
        }

        StringWriter stringWriter = new StringWriter();
        Writer out = new BufferedWriter(stringWriter);
        try {
   
            template.process(dataMap,out);
        } catch (TemplateException e) {
   
            logger.error(e.getMessage(),e);
            throw e;
        }finally 

本文标签: 动态FreemarkerPDFword