Java读取office-word(doc、docx)里面表格中的数据

这篇博客展示了如何使用Apache POI库来读取Word文档中的表格数据,包括doc和docx两种格式。通过示例代码,详细解释了如何遍历表格、行和单元格,并获取其中的内容。此外,还涉及到了Spring Boot和MongoDB的集成,用于存储读取到的数据。

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

  • 依赖
        <!--Java读取word中的表格数据-->
        <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>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.1.2</version>
        </dependency>
  • 代码

import com.alibaba.fastjson.JSON;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HandleDataTest {
    @Autowired
    MongoTemplate mongoTemplate;


    // 读取doc文档中表格数据示例
    /**
     * 读取文档中表格
     * @param
     */
    @Test
    public void testWord(){

        System.err.println("开始读取");
        String filePath = "G:\\项目文件\\附件3-代码 - 副本.doc";
        System.err.println("结束读取");

        List<Subject> resultList = new ArrayList<>();

        try{
            FileInputStream in = new FileInputStream(filePath);//载入文档
            // 处理docx格式 即office2007以后版本
            if(filePath.toLowerCase().endsWith("docx")){
                //word 2007 图片不会被读取, 表格中的数据会被放在字符串的最后
                XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
                Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
                // 设置需要读取的表格  set是设置需要读取的第几个表格,total是文件中表格的总数
                int set = 1, total = 2;
                int num = set;
                // 过滤前面不需要的表格
              /*  for (int i = 0; i < set-1; i++) {
                    it.hasNext();
                    it.next();
                }*/
                while(it.hasNext()){
                    XWPFTable table = it.next();
                    System.out.println("这是第" + num + "个表的数据");
                    List<XWPFTableRow> rows = table.getRows();
                    //读取每一行数据
                    for (int i = 0; i < rows.size(); i++) {
                        XWPFTableRow  row = rows.get(i);
                        System.err.println("第"+i+"行:");
                        //读取每一列数据
                        List<XWPFTableCell> cells = row.getTableCells();
                        for (int j = 0; j < cells.size(); j++) {
                            XWPFTableCell cell = cells.get(j);
                            //输出当前的单元格的数据
                            System.out.print("第"+j+"列:"+cell.getText() + "\t");
                        }
                        System.out.println();
                    }
                    // 过滤多余的表格
                 /*   while (num < total) {
                        it.hasNext();
                        it.next();
                        num += 1;
                    }*/
                }
            }else{
                // 处理doc格式 即office2003版本
                POIFSFileSystem pfs = new POIFSFileSystem(in);
                HWPFDocument hwpf = new HWPFDocument(pfs);
                Range range = hwpf.getRange();//得到文档的读取范围
                TableIterator it = new TableIterator(range);
                // 迭代文档中的表格
                // 如果有多个表格只读取需要的一个 set是设置需要读取的第几个表格,total是文件中表格的总数
                int set = 1, total = 10;
                int num = total;
                for (int i = 0; i < set-1; i++) {
                    it.hasNext();
                    it.next();
                }
                while (it.hasNext()) {
                    Table tb = (Table) it.next();
                    System.out.println("这是第" + num + "个表的数据");
                    //迭代行,默认从0开始,可以依据需要设置i的值,改变起始行数,也可设置读取到那行,只需修改循环的判断条件即可
                    for (int i = 0; i < tb.numRows(); i++) {

                        Subject subject = new Subject();


                        TableRow tr = tb.getRow(i);
                        //迭代列,默认从0开始
//                        for (int j = 0; j < tr.numCells(); j++) {
                        for (int j = 0; j < tr.numCells()-1; j++) {
                            TableCell td = tr.getCell(j);//取得单元格
                            //取得单元格的内容
                            for(int k = 0; k < td.numParagraphs(); k++){
                                Paragraph para = td.getParagraph(k);
                                String s = para.text();
                                //去除后面的特殊符号
                                if(null != s && !"".equals(s)){
                                    s = s.substring(0, s.length()-1);
                                }

                                if(j == 0){
                                    subject.setCode(s);
                                }
                                if(j == 1){
                                    subject.setName(s);
                                }

                                System.out.print("---" + s + "\t");
                            }
                        }
                        //将数据保存到数据库中
                        mongoTemplate.save(subject);
                        resultList.add(subject);

                        System.out.println();
                    }
                    // 过滤多余的表格
                    while (num < total) {
                        it.hasNext();
                        it.next();
                        num += 1;
                    }
                }
            }
            System.out.println("一共:" + resultList.size() + " 个");

        }catch(Exception e){
            e.printStackTrace();
        }
//        System.out.println(JSON.toJSONString(resultList, true));
    }




}

### Java 使用 POI 库读取和写入 Word 文档 (.docx) 中的表格 为了实现对 `.docx` 文件中表格数据的操作,Java 的 Apache POI 是一个非常强大的工具库。通过该库能够有效地处理 Microsoft Office 格式的文件。 #### 导入库 首先,在项目中引入必要的依赖项来支持 `POI` 功能: 对于 Maven 项目,可以在 pom.xml 添加如下配置: ```xml <dependencies> <!-- Other dependencies --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.3</version> </dependency> </dependencies> ``` #### 创建读取功能 下面是一个简单的例子展示如何利用 POI 来读取 `.docx` 文件内的表格内容: ```java import org.apache.poi.xwpf.usermodel.*; import java.io.FileInputStream; import java.util.List; public class ReadDocxTable { public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream("path/to/your/document.docx"); XWPFDocument document = new XWPFDocument(fis); List<XWPFTable> tables = document.getTables(); for (XWPFTable table : tables) { System.out.println("-- Table Start --"); // 遍历每一行 for (XWPFTableRow row : table.getRows()) { StringBuilder lineBuilder = new StringBuilder("| "); // 获每列的内容 for (XWPFTableCell cell : row.getTableCells()) { String text = cell.getText().trim(); lineBuilder.append(text).append(" | "); } System.out.println(lineBuilder.toString()); } System.out.println("-- Table End --\n"); } document.close(); fis.close(); } } ``` 这段代码会遍历指定路径下的 `.docx` 文件里的所有表格,并打印出其中的文字信息[^1]。 #### 实现写入功能 如果想要向现有的 `.docx` 文件添加新的表格或是修改已有的表格,则可以通过以下方式完成: ```java import org.apache.poi.xwpf.usermodel.*; import java.io.FileOutputStream; import java.io.IOException; public class WriteToDocxTable { public static void writeNewRow(XWPFTable table, String... cellsContent) { int rowIndex = table.getNumberOfRows(); // 新增行的位置 // 插入新行到表尾部 XWPFTableRow newRow = table.createRow(); for(int i=0; i<cellsContent.length && i<table.getRow(0).getTableCells().size(); ++i){ newRow.getCell(i).setText(cellsContent[i]); } } public static void main(String[] args)throws IOException{ try(FileOutputStream out = new FileOutputStream("output_document.docx")) { XWPFDocument doc = new XWPFDocument(); XWPFTable tbl = doc.createTable(); // 填充初始数据作为示例 writeNewRow(tbl,"Header1","Header2"); writeNewRow(tbl,"DataA1","DataB1"); doc.write(out); doc.close(); } catch(IOException e){ throw new RuntimeException(e.getMessage(),e); } } } ``` 此段程序创建了一个包含两列的新表格,并往里面填入了几条记录;最后保存至磁盘上的目标位置[^3]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值