使用POI按照顺序解析word文档,有文字有表格

1、需求

将word文档中的内容解析,并存储到数据库中,word中有标题、有段落文字、有表格,并且这三者要保证顺序,因为还要对数据进行修改后进行导出的操作

2、所需依赖

<!-- poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
</dependency>
<!-- end poi -->

3、开始解析

public String importWordExpProgram(MultipartFile file) {
        //文档元素集合下标
        private int docIndex = 0;
        //段落集合下标
        private int pIndex = 0;
        //表格集合下标
        private int tableIndex = 0;

        try (InputStream inputStream = file.getInputStream()) {
            XWPFDocument xdoc = new XWPFDocument(inputStream);
            //拿到word文档中的元素集合、段落集合、表格集合
            List<IBodyElement> bodyElementList = xdoc.getBodyElements();
            List<XWPFParagraph> paragraphList = xdoc.getParagraphs();
            List<XWPFTable> tableList = xdoc.getTables();
            //遍历元素集合
            for (; docIndex < bodyElementList.size(); docIndex++) {
                //如果元素属于段落类型
                if (bodyElementList.get(docIndex).getElementType() == BodyElementType.PARAGRAPH) {
                    //对段落进行操作
                    System.out.println(paragraphList.get(pIndex).getText());
                    pIndex++;
                } else if (bodyElementList.get(docIndex).getElementType() == BodyElementType.TABLE) {
                    //如果元素属于表格类型,对表格进行解析,先拿到表格所有的行
                    List<XWPFTableRow> rows = tableList.get(tableIndex).getRows();
                    tableIndex++;
                    //遍历表格中的每个元素
                    for (int i = 0; i < rows.size(); i++) {
                        List<XWPFTableCell> tableCells = rows.get(i).getTableCells();
                        for (int j = 0; j < tableCells.size(); j++) {
                            //对表格单元值进行操作
                            System.out.println(tableCells.get(j).getText());
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return '解析word文档成功~';
    }

这是最基础的解析工作,可以按照word中的顺序依次打印文字和表格,可以配合其它代码来读取标题等级并分批次将数据保存到数据库中。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值