Java往Word文档中的表格写数据

在日常的开发中,我们经常需要将数据写入到Word文档中,而表格是Word文档中常用的数据展示方式之一。本文将介绍如何使用Java将数据写入Word文档的表格中,并提供相应的代码示例。

准备工作

在使用Java操作Word文档之前,我们需要添加相应的依赖包。在本文中,我们将使用Apache POI库来操作Word文档。在项目的pom.xml文件中,添加如下依赖:

<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>

创建Word文档和表格

首先,我们需要创建一个空的Word文档,并在其中添加一个表格。下面的代码示例演示了如何创建一个含有3行4列的表格:

import org.apache.poi.xwpf.usermodel.*;

import java.io.FileOutputStream;
import java.io.IOException;

public class WordTableExample {

    public static void main(String[] args) {
        try (XWPFDocument document = new XWPFDocument()) {
            // 创建表格
            XWPFTable table = document.createTable(3, 4);

            // 设置表格样式
            CTTblPr tableProperties = table.getCTTbl().getTblPr();
            CTTblWidth tableWidth = tableProperties.addNewTblW();
            tableWidth.setType(STTblWidth.DXA);
            tableWidth.setW(BigInteger.valueOf(5000));

            // 添加表头
            XWPFTableRow headerRow = table.getRow(0);
            headerRow.getCell(0).setText("Header1");
            headerRow.getCell(1).setText("Header2");
            headerRow.getCell(2).setText("Header3");
            headerRow.getCell(3).setText("Header4");

            // 添加数据行
            for (int row = 1; row < 3; row++) {
                XWPFTableRow dataRow = table.getRow(row);
                for (int col = 0; col < 4; col++) {
                    dataRow.getCell(col).setText("Data" + (row - 1) + "-" + col);
                }
            }

            // 保存文档
            try (FileOutputStream outputStream = new FileOutputStream("example.docx")) {
                document.write(outputStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上述代码中,我们首先创建了一个空的XWPFDocument对象,该对象代表了一个Word文档。然后,我们使用createTable方法创建了一个3行4列的表格,并设置了表格的宽度。接着,我们添加了表头和数据行,并设置了每个单元格的文本内容。最后,我们通过FileOutputStream将文档保存到本地。

运行代码和查看结果

将上述代码保存为WordTableExample.java文件,并编译运行。执行成功后,会在当前目录下生成一个名为example.docx的Word文档。我们可以使用Word软件打开该文档,查看表格中的数据。

结语

本文介绍了如何使用Java将数据写入Word文档的表格中。通过使用Apache POI库,我们可以方便地操作Word文档,并实现灵活的数据展示。希望本文对你有所帮助,谢谢阅读!

erDiagram
    Word文档 }|..|XWPFDocument
    XWPFDocument }|..|XWPFTable
    XWPFTable }|..|XWPFTableRow
    XWPFTableRow }|..|XWPFTableCell
    XWPFTableCell }--|数据内容|