spring-boot+freemarker完美导出word文档

本文介绍如何使用Freemarker模板引擎结合Java生成Word文档,包括添加依赖、模板制作、工具类创建及业务实现,适合希望自动化文档生成的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:初次接触,没来的及优化,凑合看吧。

1.pom文件添加依赖。

<!-- freemarker -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.20</version>
        </dependency>

2.新建images和templage文件夹准备存放你的图片和模板。你也可以存放到其他地方,能找到就行。

3.模板制作。

    ①.打开WPS或者Office编辑word文档。我用的是WPS。

    ②.另存为xml文件。文件名就叫template.xml.

    ③.用其他编辑器打开template.xml文件。我用的是EditPlus 3。将需要注入数据的地方修改为${xxx}格式,并且记住你的字段名,如果有多条数据则添加<#list userList as user><#list>标签,userList是Map里的key。

    ④.编辑好之后另存为.ftl文件。这就是模板。可以存放到项目里的templage里。再往images里传一张图片。

4.创建模板生成工具类。


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.utility.DateUtil;

public class WordUtils {
    
    private static Configuration configuration = null;
        //classLoader.getResource()只能获取相对路径的资源
//     private static final String templateFolder = WordUtils.class.getClassLoader().getResource("template").getPath();
        //class.getResource()可以获取绝对路径和相对路径
        private static final String templateFolder = WordUtils.class.getResource("/template").getPath();


    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        try {
            configuration.setDirectoryForTemplateLoading(new File(templateFolder));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private WordUtils() {
        throw new AssertionError();
    }

    public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map, String title, String ftlFile) throws IOException {
        Template freemarkerTemplate = configuration.getTemplate(ftlFile);
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            // 调用工具类的createDoc方法生成Word文档
            file = createDoc(map, freemarkerTemplate);
            fin = new FileInputStream(file);

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件名
            String fileName = title + DateUtils.getDate() + ".doc";
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));

            out = response.getOutputStream();
            byte[] buffer = new byte[512];  // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } finally {
            if (fin != null) fin.close();
            if (out != null) out.close();
            if (file != null) file.delete(); // 删除临时文件
        }
    }

    private static File createDoc(Map<?, ?> dataMap, Template template) {
        String name = "sellPlan.doc";
        File f = new File(name);
        Template t = template;
        try {
            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }
}

6.业务类,我直接与controller写到了一块。

@RequestMapping("/exportSellPlan")
    public @ResponseBody void exportSellPlan(HttpServletRequest request, HttpServletResponse response) {
        Calendar calendar = Calendar.getInstance();// 取当前日期。
        String imagePath = WordUtils.class.getResource("/images").getPath()+"/image2.jpg";
            //获得数据
       List<User> users = userService.getUsers();
       Map<String, Object> map = new HashMap<String, Object>();
        map.put("text", "我想大声告诉你,你一直在我世界里。");
        map.put("userList", users);
        map.put("image",this.getImageBase(imagePath));
            try {
                WordUtils.exportMillCertificateWord(request, response, map, "方案", "template.ftl");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

    //获得图片的base64码
      @SuppressWarnings("deprecation")
      public String getImageBase(String src) {
            if(src==null||src==""){
                    return "";
                }
           File file = new File(src);
           if(!file.exists()) {
                   return "";
                }
               InputStream in = null;
               byte[] data = null;
               try {
                      in = new FileInputStream(file);
                  } catch (FileNotFoundException e1) {
                      e1.printStackTrace();
                  }
             try {
                      data = new byte[in.available()];
                      in.read(data);
                      in.close();
                  } catch (IOException e) {
                    e.printStackTrace();
                  }
                BASE64Encoder encoder = new BASE64Encoder();
                return encoder.encode(data);
            }

OK!

搞定!

启动项目,输入localhost:8080/exportSellPlan

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值