SpringBoot 使用FreeMarker根据模板生成word文件

1. pom文件中引入FreeMarker依赖

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

2. 使用word 创建模板文档如图

 

3. 将word文档另存为xml格式,同时将变量修改为${variable}格式

4.将xml文件后缀名改为ftl格式

5.将ftl文件放在/templates/目录下

6.代码实现:

工具类:

package com.example.demo.common;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

public class CreateWordUtil {

    public static  void createWord(Map dataMap){
        try {
            //Configuration 用于读取ftl文件
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            //获取根目录
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if(!path.exists()) path = new File("");
            System.out.println("path:"+path.getAbsolutePath());
            //如果上传目录为/templates/,则可以如下获取:
            File upload = new File(path.getAbsolutePath(),"templates/");
            if(!upload.exists()) upload.mkdirs();
            System.out.println("upload url:"+upload.getAbsolutePath());
            //指定路径的第一种方式,
            //configuration.setClassForTemplateLoading();
            //指定路径的第二种方式,具体路径
            configuration.setDirectoryForTemplateLoading(upload);
            //输出文档路径及名称
            File outFile = new File("D:/报销信息导出.doc");
            //以utf-8的编码读取ftl文件
            Template template = configuration.getTemplate("puser.ftl", "utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            template.process(dataMap, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

测试类

package com.example.demo.controller;

import com.example.demo.common.CreateWordUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/demo")
public class DemoController {

    @GetMapping("/test")
    public void test() {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        ///姓名
        dataMap.put("name", "张三");
        //年龄
        dataMap.put("age", 15);
        //地址
        dataMap.put("address","山西省");
        //其他
        dataMap.put("other","其他");
        CreateWordUtil.createWord(dataMap);
    }
}

测试结果:

D盘目录下正常生成文件。内容如下:

您好!对于Spring Boot使用Freemarker模板生成Word文档并加密的例子,可以按照以下步骤进行操作: 1. 首先,您需要在pom.xml文件中添加Freemarker和Apache POI的依赖项。在 `<dependencies>` 标签内添加以下代码: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 2. 创建一个Freemarker模板文件,例如 `template.ftl`,并在其中编写Word文档的内容,可以使用Freemarker语法进行动态内容替换。 3. 创建一个Controller类,并添加以下代码: ```java import freemarker.template.Configuration; import freemarker.template.Template; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFEncryptor; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; @Controller public class WordController { @Autowired private Configuration freemarkerConfiguration; @GetMapping("/generate-word") public void generateWord(HttpServletResponse response) throws Exception { // 加载Freemarker模板 Template template = freemarkerConfiguration.getTemplate("template.ftl"); // 创建Word文档对象 XWPFDocument document = new XWPFDocument(); // 创建段落对象 XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); // 填充模板内容 Map<String, Object> data = new HashMap<>(); // 添加模板中需要的数据,可以根据实际需求自行修改 // 渲染模板 run.setText(templateToString(template, data)); // 加密Word文档 XWPFEncryptor encryptor = new XWPFEncryptor(document); encryptor.encrypt("password"); // 替换为您自己的密码 // 设置响应头 response.setHeader("Content-disposition", "attachment; filename=encrypted_word.docx"); response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); // 导出Word文档 OutputStream outputStream = response.getOutputStream(); document.write(outputStream); outputStream.close(); } private String templateToString(Template template, Map<String, Object> data) throws Exception { StringWriter stringWriter = new StringWriter(); template.process(data, stringWriter); return stringWriter.toString(); } } ``` 4. 在Spring Boot的配置文件(例如 `application.properties`)中添加以下配置: ```properties spring.freemarker.template-loader-path=classpath:/templates/ ``` 5. 运行Spring Boot应用程序,并访问 `/generate-word` 路径,即可生成并下载加密的Word文档。 请注意,上述代码仅为示例,您可以根据实际需求进行修改和扩展。同时,为了确保文档的安全性,请根据您的需求修改加密密码和文件名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值