使用freemaker模板生成word文件并填充数据

1.java代码 

/**
     * 使用word模板生成文件(xxx.ftl)
     * @param request
     * @param documentOperation//模板信息实体类
     */
    private String generateFile(HttpServletRequest request, DocumentOperation documentOperation) {
        String filePath = null;

        Map<String, Object> params = new HashMap<String, Object>();

        Writer out = null;
        try {

            //取得要填充的相关信息数据
            params = fillDataUtils.fileDocumentData(dacasCaseNews);
            Configuration cfg = new Configuration();
            cfg.setDefaultEncoding("UTF-8");
            ServletContext servletContext = request.getSession().getServletContext();
            cfg.setServletContextForTemplateLoading(servletContext, "/templates");
            //获取模板
            Template tmp = cfg.getTemplate(documentOperation.getTemplateFile(), "UTF-8");

            String filename = documentOperation.getTemplateFileName() + DateUtils.dateToString(new Date(),"yyyyMMddHHmmss") +".doc";

            filePath = getGeneratePath(filename);//拼接文件写入的路径,判断不存在创建

            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"));
            tmp.process(params, out);


        } catch (Exception ex) {
            logger.error("", ex);
        }finally {
            if(out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return filePath;
    }

2.freemarker需要jar依赖可以网上找一下,以下是gradle的jar配置

3.将画好的word文件(xx.doc)修改后缀名会生成xml文件,或者改为.ftl文件,使用freemarker标签填充数据

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!对于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、付费专栏及课程。

余额充值