springboot下使用freemarker导出复杂的excel模板传给前端流

这篇博客介绍了如何在SpringBoot项目中使用Freemarker代替Easypoi来生成Excel文件。作者详细阐述了配置Freemarker依赖、设置模板字段、后台代码实现以及模板文件的存储位置。通过Freemarker的模板语法,实现了数据遍历和处理,解决了前端无法解析XML的问题,使得前端能够成功解析二进制数据。
摘要由CSDN通过智能技术生成

用easypoi遇到了一些问题,然后该用freemarker

我是使用的springboot集成的!

先看一下我的模板有多么复杂

 先说一下步骤

1.先导入freemarker的依赖

<!--freemarker start-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    <dependency>
      <groupId>freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.8</version>
    </dependency>
    <!--freemarker end-->

2.将你的模板文件添加相应的字段

然后另存为xml格式,然后利用xml格式化工具将其格式化,你就会得到如下的

解释一下这里的数据,一个list就是你后台请求数据返回的一个list,然后这样写语法,freemarker就会遍历,有多条,循环出来的就是多条数据

这是正确的,你需要判空,需要加!,这都是freemarker的语法,这里贴一个freemarker的模板语法网址freemarker模板网址

然后我就直接贴后台代码了

    /** 数据类型为{@value} .*/
    public static final String UTF_8 = "UTF-8";

    /**
     * 构造方法.
     */
    private FreemarkerExcelUtil() {
    }

    /**
     * @param dataMap 传入的数据
     * @param valueName 存储名
     * @return file
     */
    public static byte[] createExcel(final Map<?, ?> dataMap,
                                   final String valueName) throws IOException, TemplateException {
        final Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding(UTF_8);
        configuration.setClassForTemplateLoading(FreemarkerExcelUtil.class, "/export-model");
        final Template template = configuration.getTemplate(valueName);
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final Writer w = new OutputStreamWriter(outputStream, UTF_8);
        template.process(dataMap, w);
        w.close();
        return outputStream.toByteArray();

    }
    /** 数据类型为{@value} .*/
    public static final String UTF = "UTF-8";


    /**
     * 调用创建excel帮助类,来创建excel.
     * @param request 请求
     * @param response 响应
     * @param dataMap 传过来的map
     * @param valueName 存储名
     * @param fileName 文件名
     */
    @Override
    public void excelUtil(final HttpServletRequest request,
                          final HttpServletResponse response,
                          final Map<?, ?> dataMap,
                          final String valueName,
                          final String fileName) throws IOException, TemplateException {
        byte[] file = FreemarkerExcelUtil.createExcel(dataMap, valueName);
        try (OutputStream out = response.getOutputStream();) {
            request.setCharacterEncoding(UTF);
            //调用创建excel帮助类,其中LeaderHomepage.ftl为模板名称  路径export-model/LeaderHomepage.ftl
            response.setCharacterEncoding(UTF);
            response.setContentType("application/msexcel");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls", UTF));
            out.write(file);
            out.flush();
        }
    }

最后贴一个模板在idea项目中存放的位置,注意是ftl格式的,你将xml加完freemarker的语法就可以改文件的后缀为.ftl了。

我之前百度的做法,传给前段的是xml,前端解析不了,做好是二进制,但是后来改成了这样。前台就可以解析了

在 Spring Boot 中集成 Freemarker 导出 Excel,可以通过以下步骤实现: 1. 首先,需要在 Spring Boot 中添加 Freemarker 和 Apache POI 依赖: ```xml <dependencies> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>${freemarker.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>${apache.poi.version}</version> </dependency> </dependencies> ``` 2. 创建 Excel 模板文件,可以使用 Freemarker模板语法来定义表头和数据内容,同时在模板中可以使用 `img` 标签来引用图片,例如: ```html <html> <head> <title>Excel Template</title> </head> <body> <table> <thead> <tr> <th>Name</th> <th>Age</th> <th>Photo</th> </tr> </thead> <tbody> <#list users as user> <tr> <td>${user.name}</td> <td>${user.age}</td> <td><img src="${user.photo}" /></td> </tr> </#list> </tbody> </table> </body> </html> ``` 其中,`users` 是一个包含数据的列表,每个元素是一个包含 `name`、`age` 和 `photo` 属性的对象,`photo` 属性是图片的 URL。 3. 在 Spring Boot 中定义一个控制器,用于处理导出 Excel 的请求: ```java @Controller public class ExcelController { @Autowired private Configuration freemarkerConfig; @GetMapping("/export") public void exportExcel(HttpServletResponse response) throws Exception { // 读取 Excel 模板文件 Template template = freemarkerConfig.getTemplate("excel-template.ftl"); // 准备数据 List<User> users = prepareData(); // 创建 Excel 工作簿 Workbook workbook = new XSSFWorkbook(); // 渲染模板,生成 Excel 文件 Map<String, Object> model = new HashMap<>(); model.put("users", users); StringWriter out = new StringWriter(); template.process(model, out); InputStream is = new ByteArrayInputStream(out.toString().getBytes("UTF-8")); workbook = WorkbookFactory.create(is); // 设置响应头,告诉浏览器文件类型是 Excel response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-disposition", "attachment; filename=users.xlsx"); // 将 Excel 文件写入响应中 OutputStream os = response.getOutputStream(); workbook.write(os); os.flush(); os.close(); } private List<User> prepareData() { // TODO: 从数据库或其他来源读取数据 return Arrays.asList( new User("Alice", 25, "https://example.com/alice.jpg"), new User("Bob", 30, "https://example.com/bob.jpg"), new User("Charlie", 20, "https://example.com/charlie.jpg") ); } private static class User { private String name; private int age; private String photo; public User(String name, int age, String photo) { this.name = name; this.age = age; this.photo = photo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } } } ``` 在该控制器中,我们注入了 `Configuration` 类,它是 Freemarker 的配置类,用于加载 Excel 模板文件。在 `exportExcel` 方法中,我们先准备数据,然后通过 `template.process` 方法渲染模板,生成 Excel 文件。最后将 Excel 文件写入响应中,浏览器会自动下载该文件。 4. 如果 Excel 模板中包含图片,那么需要在渲染模板之前,将图片下载到本地,然后将图片的本地路径传递给模板。例如: ```java private String downloadImage(String imageUrl) throws Exception { URL url = new URL(imageUrl); String fileName = url.getFile(); String filePath = "images/" + fileName.substring(fileName.lastIndexOf("/") + 1); FileUtils.copyURLToFile(url, new File(filePath)); return filePath; } @GetMapping("/export") public void exportExcel(HttpServletResponse response) throws Exception { // 读取 Excel 模板文件 Template template = freemarkerConfig.getTemplate("excel-template.ftl"); // 准备数据 List<User> users = prepareData(); // 下载图片并将本地路径传递给模板 for (User user : users) { String photoPath = downloadImage(user.getPhoto()); user.setPhoto(photoPath); } // 创建 Excel 工作簿 Workbook workbook = new XSSFWorkbook(); // 渲染模板,生成 Excel 文件 Map<String, Object> model = new HashMap<>(); model.put("users", users); StringWriter out = new StringWriter(); template.process(model, out); InputStream is = new ByteArrayInputStream(out.toString().getBytes("UTF-8")); workbook = WorkbookFactory.create(is); // 设置响应头,告诉浏览器文件类型是 Excel response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-disposition", "attachment; filename=users.xlsx"); // 将 Excel 文件写入响应中 OutputStream os = response.getOutputStream(); workbook.write(os); os.flush(); os.close(); } ``` 在该示例中,我们定义了一个 `downloadImage` 方法,用于下载图片,并将图片保存到 `images` 目录下。然后在 `exportExcel` 方法中,遍历用户列表,调用 `downloadImage` 方法下载每个用户的图片,并将本地路径传递给模板。注意,模板使用的图片路径应该和下载到本地的路径一致。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值