两步实现springBoot导出带动态表格的word docx文档

1.第一步 导入poi依赖

复制代码
<!-- Apache POI -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>

        <!-- Apache POI OOXML -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
复制代码

2.第二步 创建导出接口

复制代码
package com.mybatis.plus.controller;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.math.BigInteger;
import java.util.Objects;

@Controller

public class WordExportController {

    @GetMapping("/export")
    public void exportWord(HttpServletResponse response) throws IOException {
        // 创建一个新的Word文档

        XWPFDocument document = new XWPFDocument();

        // 添加段落1
        addParagraph(document, "1.段落1");

        // 添加内容
        addContent(document,"我是内容XXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        addContent(document,"我是内容XXXXXXXXXXXXXXXXXXXXXXXXXXXX");

        // 添加段落2
        addParagraph(document, "2.段落2");

        // 添加表格
        List<String> headers = Arrays.asList("姓名", "年龄", "成绩");
        List<List<String>> data = Arrays.asList(
                Arrays.asList("张三", "5", "20"),
                Arrays.asList("李四", "5", "60")
        );
        addTable(document, headers, data);

        // 设置响应头信息
        response.setHeader("Content-Disposition", "attachment; filename=word_export.docx");
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");

        // 将文档写入输出流
        document.write(response.getOutputStream());
        document.close();
    }

    /**
     * @author: gch
     * @Description: 添加基础文本内容
     * @Date: 2023/8/19 12:12
     * @Param: 
     * @return: 
     */
    private void addContent(XWPFDocument document, String content) {
        document.createParagraph().createRun().setText(content);
    }

    /**
     * @author: gch
     * @Description: 添加段落
     * @Date: 2023/8/19 12:11
     * @Param: 
     * @return: 
     */
    private void addParagraph(XWPFDocument document, String s) {
        XWPFParagraph paragraph1 = document.createParagraph();
        paragraph1.setAlignment(ParagraphAlignment.LEFT);
        XWPFRun run1 = paragraph1.createRun();
        run1.setBold(true);
        run1.setFontSize(16); // 设置标题字体大小
        run1.setText(s);
    }

    /**
     * @author: gch
     * @Description: 添加动态表格
     * @Date: 2023/8/19 12:11
     * @Param:
     * @return:
     */
    private void addTable(XWPFDocument document, List<String> headers, List<List<String>> data) {
        Integer rowNum = 1;
        if (!Objects.isNull(data.get(0))) {
            rowNum = data.get(0).size();
        }
        // 添加表格
        XWPFTable table = document.createTable(rowNum, headers.size()); // 创建一个3行3列的表格
        // 设置表头
        for (int col = 0; col < headers.size(); col++) {
            XWPFTableCell cell = table.getRow(0).getCell(col);
            cell.setText(headers.get(col));
            cell.setWidth("1000");
            addCellCenterStyle(cell);
        }
        // 设置示例数据
        for (int row = 0; row < data.size(); row++) {
            for (int col = 0; col < headers.size(); col++) {
                XWPFTableCell cell = table.getRow(row + 1).getCell(col);
                cell.setText(data.get(row).get(col));
                cell.setWidth("1000");
                addCellCenterStyle(cell);
            }
        }
    }

    /**
     * @author: gch
     * @Description: 添加水平居中韩国样式
     * @Date: 2023/8/19 12:11
     * @Param: 
     * @return: 
     */
    private void addCellCenterStyle(XWPFTableCell cell) {
        CTTc ctTc = cell.getCTTc();
        //获取 CTP
        CTP ctP = (ctTc.sizeOfPArray() == 0) ?
                ctTc.addNewP() : ctTc.getPArray(0);
        //获取段落
        XWPFParagraph par = cell.getParagraph(ctP);
        //设置水平居中
        par.setAlignment(ParagraphAlignment.CENTER);
    }
}
复制代码

 

运行结果:

 

posted @   官萧何  阅读(1300)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示