SpringBoot 使用freemarker 处理文档,找不到文件位置(报错:basePackagePath=““ /* relatively to resourceLoaderClass pkg)

在Spring Boot中加载word的文档的时候,加载ftl文档的位置应该是从 target目录下面去加载的(不太确定),不是像大多数情况这样根据类的路径去加载。SpringBoot加载的位置应该是从 “resources”文件下面开始,如果放到“resources”的根目录下面需要加一道“/”斜线。

类似于:

configuration.setClassForTemplateLoading(类名.class,"/ ");

这个时候的类名就与本类没有太大关系了,而是任意的类名即可,都会从这个目录下面去加载文件。

如果是放在该目录下面的static文件下面,就要把目录改成“/static/”即可。后面有“/”没有影响,因为在获取的时候会进行判断。

一端完整的获取配置的代码和文件位置在目录的放置关系。

 

package com.example.demo;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: WordBoot
 * @Author WDF
 * @Description 测试SpringBoot生成word文档
 * @Date 2020/9/19 14:04
 * @Copyright WDF 2020/9/19
 * @Version 1.0
 **/
@Controller
@RequestMapping("/word")
public class WordBoot {

    /**
     * @return java.lang.String
     * @Author WDF
     * @Description 调用接口生成word文档
     * @Date 2020/9/19 14:57
     * @Param []
     **/
    @RequestMapping("/test")
    @ResponseBody
    public String outWord() {
        try {
            WordBoot.createWord();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件下载失败");
        }
        return "ok";
    }

    /**
     * 生成word文件
     */
    public static void createWord() {

        String templateName = "testword1.ftl";//word模板名称
        String filePath = "D:\\freemarker";//文件生成的目标路径,保存word文档的路径
        String fileName = "Test.doc";//生成的word文件名称
        try {
            //创建配置实例
            Configuration configuration = new Configuration();

            //设置编码
            configuration.setDefaultEncoding("utf-8");

            //ftl模板文件
            configuration.setClassForTemplateLoading(WordBoot.class, "/static/template/");

            //获取模板
            Template template = configuration.getTemplate(templateName);

            //输出文件
            File outFile = new File(filePath + File.separator + fileName);

            //如果输出目标文件夹不存在,则创建
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }

            //将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
            Map<String, Object> dataMap1 = new HashMap<String, Object>();
            getFillData(dataMap1);
            //生成文件
            template.process(dataMap1, out);

            //关闭流
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void getFillData(Map dataMap) {
        // 根据模板中的参数填充内容,可以不按顺序,参数名称要对上
        dataMap.put("wordname", "文档标题123");
        dataMap.put("user", "userName");
        dataMap.put("password", "12345");
        dataMap.put("wordDescription", "描述内容");
        dataMap.put("para", "变量");
        dataMap.put("type", "类型");
        dataMap.put("empty", "不可空");
    }
}

 参考:https://blog.csdn.net/qq_40693828/article/details/85138084

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
您好!对于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文档。 请注意,上述代码仅为示例,您可以根据实际需求进行修改和扩展。同时,为了确保文档的安全性,请根据您的需求修改加密密码和文件名。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值