SpringBoot + Poi-tl实现word模板导出数据表格

一、poi-tl官网

1. 地址:

https://deepoove.com/poi-tl/

2. 版本:1.5 版本

在这里插入图片描述

3. 引入Maven

<dependency>
    <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.5.1</version>
</dependency>

二、单个表格在word导出

1. 模板必须是docx,也就是:

在这里插入图片描述

2. 模板

在这里插入图片描述

3. 代码

public void test1(HttpServletRequest request, HttpServletResponse response){
        TableStyle tableStyle = new TableStyle();
        tableStyle.setBackgroundColor("F2F2F2");
        tableStyle.setAlign(STJc.CENTER);

        Style style = StyleBuilder.newBuilder().buildBold().buildFontSize(10).build();
        RowRenderData header = RowRenderData.build(
                new TextRenderData("序号", style),
                new TextRenderData("表名", style),
                new TextRenderData("描述", style));
        header.setRowStyle(tableStyle);

        Map<String, Object> mapp = new HashMap<>();
        List<RowRenderData> list = new ArrayList<>();
        List<Map<String, Object>> mapList = ***Service.test1();
        for (Map<String, Object> map : mapList) {
            RowRenderData rowRenderData = RowRenderData.build(
                    map.get("xh").toString(),
                    map.get("name").toString(),
                    map.get("comment") != null ? map.get("comment").toString() : null
            );
            list.add(rowRenderData);
        }
        // tables 就是模板定义的那个
        mapp.put("tables", new MiniTableRenderData(header, list));

        try {
            // 模板
            XWPFTemplate template = XWPFTemplate.compile("C:\\Users\\***\\Desktop\\bbbb.docx").render(mapp);
            // 生成的文件
            FileOutputStream out = new FileOutputStream("C:\\Users\\***\\Desktop\\out_.docx");
            template.write(out);
            out.flush();
            out.close();
            template.close();

            InputStream fis = null;
            OutputStream toClient = null;
            File file = new File("C:\\Users\\***\\Desktop\\out_.docx");
            fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            String newWordName = URLEncoder.encode("单表模板", "utf-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + newWordName);
            response.setContentType("application/octet-stream;charset=utf-8");
            response.addHeader("Content-Length", "" + file.length());

            toClient = new BufferedOutputStream(response.getOutputStream());

            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();

            System.out.println("---------完成---------");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

4. 效果

在这里插入图片描述

三、多个表格在word里导出

1. 模板必须是docx

2. 模板

  -----需要2个模板-----

△1122.docx△
在这里插入图片描述

△5566.docx△
在这里插入图片描述

3. 代码

public void test(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 加粗、字体大小为10
        Style style = StyleBuilder.newBuilder().buildBold().buildFontSize(10).build();
        RowRenderData header = RowRenderData.build(
                new TextRenderData("字段名", style),
                new TextRenderData("类型", style),
                new TextRenderData("长度", style),
                new TextRenderData("描述", style));
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> mapList = ***Service.test();
        // 根据某值分组;可以根据具体业务情况,自行修改,下面代码可有可无。
        Map<String, List<Map<String, Object>>> groupedMap =
                mapList.stream()
                        .collect(Collectors.groupingBy(map -> map.get("tname").toString()));

        for (String key : groupedMap.keySet()) {
            List<Map<String, Object>> maps = groupedMap.get(key);

            Map<String, Object> mapp = new HashMap<>();
            List<RowRenderData> listOne = new ArrayList<>();
            for (Map<String, Object> map : maps) {

                RowRenderData rowRenderData = RowRenderData.build(
                        map.get("cname").toString(),
                        map.get("ctype").toString(),
                        map.get("clength") != null ? map.get("clength").toString() : null,
                        map.get("ccomment") != null ? map.get("ccomment").toString() : null
                );
                listOne.add(rowRenderData);
            }
            mapp.put("tname", ObjectUtils.isNotEmpty(maps.get(0).get("tcomment")) ? maps.get(0).get("tcomment") : key);
            MiniTableRenderData miniTable = new MiniTableRenderData(header, listOne);
            miniTable.setWidth(15.22f);
            // 1122.docx模板的单个表格+数据
            mapp.put("table", miniTable);
            list.add(mapp);
        }
        try {
            download(request, response, "模板数据.docx", list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
public static void download(HttpServletRequest request, HttpServletResponse response, String newWordName, List<Map<String, Object>> list) throws IOException {
        Map<String, Object> map = new HashMap<>();
        DocxRenderData info = new DocxRenderData(new File("C:\\Users\\***\\Desktop\\1122.docx"), list);
        // 将每个单表格放到 5566.docx模板
        map.put("tables", info);
        // 展示多个表格的模板
        XWPFTemplate template = XWPFTemplate.compile("C:\\Users\\***\\Desktop\\5566.docx").render(map);
        //输出文件
        FileOutputStream out = new FileOutputStream("C:\\Users\\***\\Desktop\\out_.docx");
        template.write(out);
        out.flush();
        out.close();
        template.close();

        InputStream fis = null;
        OutputStream toClient = null;
        File file = new File("C:\\Users\\***\\Desktop\\out_.docx");
        fis = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        // 解决中文乱码
        newWordName = URLEncoder.encode(newWordName, "utf-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + newWordName);
        response.setContentType("application/octet-stream;charset=utf-8");
        response.addHeader("Content-Length", "" + file.length());

        toClient = new BufferedOutputStream(response.getOutputStream());

        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();

        System.out.println("---------完成---------");
    }

4. 效果

在这里插入图片描述

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot中使用poi-tl库来导出带有合并列的Word表格并下载,您可以按照以下步骤操作: 1. 首先,确保您的Spring Boot项目中已经添加了poi-tl的依赖。您可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.deepoove</groupId> <artifactId>poi-tl</artifactId> <version>1.6.0</version> </dependency> ``` 2. 创建一个Controller来处理导出请求。例如,创建一个名为WordExportController的类,并添加一个处理导出请求的方法。 ```java import com.deepoove.poi.XWPFTemplate; import com.deepoove.poi.data.*; import com.deepoove.poi.util.BytePictureUtils; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; @Controller public class WordExportController { @GetMapping("/export") public ResponseEntity<InputStreamResource> exportWord() throws IOException { // 创建一个数据模型 List<List<String>> tableData = new ArrayList<>(); tableData.add(createRow("Merged Cells", "Cell 3")); tableData.add(createRow("Cell 4", "Cell 6")); // 使用poi-tl的XWPFTemplate来生成Word文档 XWPFTemplate template = XWPFTemplate.compile("templates/template.docx").render( new DataTable(tableData) .setHeader(createRow("Header 1", "Header 2")) .setCellWidth(2000) // 设置单元格宽度 .setHeaderCellStyle(new CellStyle().setBold(true).setColor("FFFFFF").setBgColor("336699")) .setOddRowCellStyle(new CellStyle().setColor("FFFFFF").setBgColor("99CCFF")) .setEvenRowCellStyle(new CellStyle().setColor("FFFFFF").setBgColor("CCEEFF")) ); // 将生成的Word文档转换为字节数组 ByteArrayOutputStream out = new ByteArrayOutputStream(); template.write(out); byte[] documentBytes = out.toByteArray(); // 设置下载响应的头信息 HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment", "merged_table.docx"); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); // 创建一个包含Word文档字节数组的InputStreamResource InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(documentBytes)); // 返回响应实体 return ResponseEntity.ok() .headers(headers) .body(resource); } private List<String> createRow(String cell1, String cell2) { List<String> row = new ArrayList<>(); row.add(cell1); row.add(cell2); return row; } } ``` 3. 在resources目录下创建一个名为template.docx的Word模板文件。在模板文件中,您可以根据自己的需求设置表格样式和内容。 4. 启动您的Spring Boot应用程序,并访问导出请求的URL(例如:http://localhost:8080/export)。将会自动下载名为merged_table.docx的Word文档,其中包含合并列的表格。 请确保按照您的需求修改代码,并根据模板文件的位置进行相应的调整。 希望对您有所帮助!如果您有任何其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值