Poi实现根据word模板导出-表格篇

本文介绍了如何使用ApachePOI库中的XWPFDocument和XWPFTable类,结合Java编程实现根据Word模板动态填充表格数据的过程,包括获取模板、解析、填充数据并保存为新文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

往期系列传送门:

Poi实现根据word模板导出-文本段落篇

Poi实现根据word模板导出-图表篇

(需要完整代码的直接看最后位置!!!)

前言:

word中表格数据填充是非常简单的,非常类似excel。如果你是从之前系列看过来的,应该能想到思路应该也是通过poi获取表格对象,然后通过表格对象操作里面的内容,套路都是一样的。

话不多说,直接看代码吧,这部分很简单:

@RequestMapping("/export")
public void exportWord() throws Exception {
    //获取word模板
    InputStream is = WordController.class.getResourceAsStream("/template/wordChartTemplate.docx");

    try {
        ZipSecureFile.setMinInflateRatio(-1.0d);
        // 获取docx解析对象
        XWPFDocument document = new XWPFDocument(is);
        // 填充表格数据
        changeTable(document);
        // 输出新文件
        FileOutputStream fos = new FileOutputStream("D:\\test\\test.docx");
        document.write(fos);
        document.close();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void changeTable(XWPFDocument document) {
    // 获取文档第一个表格(有几个就按顺序取)
    XWPFTable table = document.getTables().get(0);
    // 填充表格数据
    // 获取表格行数
    int numberOfRows = table.getNumberOfRows();
    for (int i = 0; i < numberOfRows; i++) {
        // 获取当前行
        XWPFTableRow row = table.getRow(i);
        // 变量循环当前行,获取单元格
        for (int j = 0; j < row.getTableCells().size(); j++) {
            // 获取当前单元格
            XWPFTableCell cell = row.getCell(j);
            if (null == cell) {
                cell = row.createCell();
            }
            // 填充单元格数据
            cell.setText("A" + i + "," + j);
        }
    }
}

效果实现:每个表格都有自己的坐标,和Excel基本一样。行列坐标都是从0开始

补充:

整个poi操作word都是基于以下maven依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<!-- 根据模板导出word -->
<dependency>
    <groupId>com.deepoove</groupId>
    <artifactId>poi-tl</artifactId>
    <version>1.12.0</version>
    <exclusions>
        <!-- 移除,解决版本冲突,再引入poi5.2.2 -->
        <exclusion>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
        </exclusion>
    </exclusions>
</dependency>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旅行程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值