使用freemarker模板引擎导出word文件

目录

第一步:创建Word模板

第二步:整理好数据,核对好数据要填充的位置

 第三步:使用工具类生成word文件

工具类:


第一步:创建Word模板

创建需要的模板

 另存为:单一网页文件

 

 文件名最好改为英文,防止后续因编码格式导出失败

 经过上面几步操作得到如下文件

 

 将这个文件放入模板

 

打开刚才移入的文件里面有很多标签,我们不需要关注那么多,只需要ctrl+f 搜索我们刚才在word写入的内容就可以,找到这个位置

 使用freemaker语法替换内容 

 到此模板已经搞定!~

第二步:整理好数据,核对好数据要填充的位置

map的key要与模板所要替换的内容名称一致

public void exportDoc(@PathVariable("id") Integer pid,HttpServletResponse response) throws Exception {
        //查询所有标题和内容
        List<BulletinDzh> list = query(pid);
        String name = list.get(0).getName();
        list.get(0).setName(null);

        Map<String, Object> dataMap = new HashMap<>(16);
        dataMap.put("list", list);
        dataMap.put("name",name);

       FileUtils.freemarkerExport(
        "E:\\idea_Project\\nanhang\\xqyp\\src\\main\\resources\\code",
        "export.mht",
        dataMap,
   "E:\\idea_Project\\nanhang\\xqyp\\src\\main\\resources\\code",name+".docx",response);
    }

 第三步:使用工具类生成word文件

  FileUtils.freemarkerExport(
    //模板文件所在的路径
    "E:\\idea_Project\\nanhang\\xqyp\\src\\main\\resources\\code",
    //模板文件的名称
    "export.mht",
    //整理好的数据
    dataMap,
    //生成的word文件存放位置
    "E:\\idea_Project\\nanhang\\xqyp\\src\\main\\resources\\code",name+".docx",response);

至此,使用freemarker模板引擎导出word文件已经成功!~

注意:如果数据有样式,导出的数据也是会带有样式.如下图所示 

工具类:

package com.sinosoft.springbootplus.emergencyrescue.util;

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

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * @author lzf
 * @date 2022-08-25-15:51
 */

public class FileUtils {

    /**
     * 使用 freemarker 生成word文档
     *
     * @param templateDir  模板所在目录路径
     * @param templateName 模板 例如:xxx.ftl
     * @param data         数据
     * @param fileSavePath 文档生成后,存放的路径
     * @param filename     生成后的文件名称,使用英文
     * @param response
     * @throws Exception
     */
    public static void freemarkerExport(String templateDir, String templateName, Map<String, Object> data, String fileSavePath, String filename, HttpServletResponse response) throws Exception {
        // 1.设置 freeMarker的版本和编码格式
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");

        // 2.设置 freeMarker生成Word文档,所需要的模板的路径
        configuration.setDirectoryForTemplateLoading(new File(templateDir));

        // 3.设置 freeMarker生成Word文档所需要的模板 ---> xxx.ftl
        Template t = null;
        try {
            // 模板文件名称
            t = configuration.getTemplate(templateName);
        } catch (IOException e) {
            throw new IOException("获取 ftl模板失败!" + e.getMessage());
        }

        // 4.生成 Word文档的全路径名称
        File outFile = new File(fileSavePath + filename);

        // 5.创建一个 Word文档的输出流
        Writer writer = null;
        try {
            writer = new OutputStreamWriter(new FileOutputStream(outFile), "utf-8");
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

        try {
            // 6.装载数据
            t.process(data, writer);

            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            response.setContentType("application/force-download");

            // 7.读取生成好的 Word文档
            File file = new File(fileSavePath + filename);
            FileInputStream is = new FileInputStream(file);
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int length;
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.flush();
            os.close();
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new IOException(e.getMessage());
        } finally {
            deleteTempFile(fileSavePath + filename);
        }
    }

    /**
     * 删除临时生成的文件
     */
    public static void deleteTempFile(String filePath) {
        File f = new File(filePath);
        f.delete();
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用 Apache POI 和 FreeMarker 来实现 Word 导出。具体步骤如下: 1. 引入依赖: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency> ``` 2. 编写模板文件,例如 `template.ftl`: ```xml <?xml version="1.0" encoding="UTF-8"?> <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"> <w:body> <w:p> <w:r> <w:t>${title}</w:t> </w:r> </w:p> <w:p> <w:r> <w:t>${content}</w:t> </w:r> </w:p> </w:body> </w:document> ``` 3. 编写 Java 代码: ```java import freemarker.template.Configuration; import freemarker.template.Template; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import java.io.*; import java.util.HashMap; import java.util.Map; public class WordExportUtil { public static void export(Map<String, Object> dataMap, String templatePath, String outputPath) throws Exception { // 1. 创建 Configuration 对象 Configuration configuration = new Configuration(Configuration.VERSION_2_3_31); configuration.setDefaultEncoding("UTF-8"); // 2. 加载模板文件 Template template = configuration.getTemplate(templatePath); // 3. 创建 Word 文档对象 XWPFDocument document = new XWPFDocument(); // 4. 填充数据到 Word 文档中 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8"); template.process(dataMap, outputStreamWriter); outputStreamWriter.flush(); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText(line); } // 5. 输出 Word 文档 FileOutputStream fileOutputStream = new FileOutputStream(outputPath); document.write(fileOutputStream); fileOutputStream.close(); } } ``` 其中,`dataMap` 是模板中需要填充的数据,`templatePath` 是模板文件的路径,`outputPath` 是输出文件的路径。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值