首页 > 编程语言 >java poi之XWPFDocument读取word内容并创建新的word(获取表格所有图片)

java poi之XWPFDocument读取word内容并创建新的word(获取表格所有图片)

时间:2024-05-14 19:43:38浏览次数:13  
标签:word 表格 imageInfo List XWPFDocument 获取 文档 poi

Poi的Word文档结构介绍

1、poi之word文档结构介绍之正文段落
一个文档包含多个段落,一个段落包含多个Runs,一个Runs包含多个Run,Run是文档的最小单元
获取所有段落:List paragraphs = word.getParagraphs();
获取一个段落中的所有Runs:List xwpfRuns = xwpfParagraph.getRuns();
获取一个Runs中的一个Run:XWPFRun run = xwpfRuns.get(index);

 

2、poi之word文档结构介绍之正文表格
一个文档包含多个表格,一个表格包含多行,一行包含多列(格),每一格的内容相当于一个完整的文档
获取所有表格:List xwpfTables = doc.getTables();
获取一个表格中的所有行:List xwpfTableRows = xwpfTable.getRows();
获取一行中的所有列:List xwpfTableCells = xwpfTableRow.getTableCells();
获取一格里的内容:List paragraphs = xwpfTableCell.getParagraphs();
之后和正文段落一样

 

注:
表格的一格相当于一个完整的docx文档,只是没有页眉和页脚。里面可以有表格,使用xwpfTableCell.getTables()获取,and so on
在poi文档中段落和表格是完全分开的,如果在两个段落中有一个表格,在poi中是没办法确定表格在段落中间的。(当然除非你本来知道了,这句是废话)。只有文档的格式固定,才能正确的得到文档的结构

 

3、poi之word文档结构介绍之页眉:
一个文档可以有多个页眉(不知道怎么会有多个页眉。。。),页眉里面可以包含段落和表格
获取文档的页眉:List headerList = doc.getHeaderList();
获取页眉里的所有段落:List paras = header.getParagraphs();
获取页眉里的所有表格:List tables = header.getTables();
之后就一样了

 

4、poi之word文档结构介绍之页脚:
页脚和页眉基本类似,可以获取表示页数的角标

 

IBodyElement -------------------迭代器(段落和表格)
XWPFComment -------------------评论(个人理解应该是批注)
XWPFSDT
XWPFFooter -------------------页脚
XWPFFootnotes -------------------脚注
XWPFHeader -------------------页眉
XWPFHyperlink -------------------超链接
XWPFNumbering -------------------编号
XWPFParagraph -------------------段落
XWPFPictureData -------------------图片
XWPFStyles -------------------样式(设置多级标题的时候用)
XWPFTable -------------------表格

pom 依赖

<dependencies>
       <!--解析doc文档HWPFDocument-->
       <dependency>
           <groupId>org.apache.poi</groupId>
           <artifactId>poi-scratchpad</artifactId>
           <version>4.1.2</version>
       </dependency>
       <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>springframework</groupId>
           <artifactId>spring-core</artifactId>
           <version>1.2.6</version>
       </dependency>
   </dependencies>

 

maven依赖

 

 

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


import java.io.*;
import java.util.List;

public class poi3 {
    public static void main(String[] args) throws IOException {

        // 获取文件输入流
        FileInputStream fileInputStream = getFileInputStream("666.docx");

        dealDocx(fileInputStream, "副本.docx");

    }

    private static FileInputStream getFileInputStream(String name) throws FileNotFoundException {
        String dir = poi3.class.getResource("").getPath() + name;
        FileInputStream fileInputStream = new FileInputStream(dir);
        return fileInputStream;
    }

    private static void dealDocx(InputStream inputStream, String newFileName) throws IOException {
        // 创建输出文件
        File file = new File(poi3.class.getResource("").getPath() + newFileName);

        // 获取文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(file);

        // 创建操作word的对象
        XWPFDocument wordInput = new XWPFDocument(inputStream);
        XWPFDocument wordOutput = new XWPFDocument();

        // 获取所有段落
        List<XWPFParagraph> xwpfParagraphs = wordInput.getParagraphs();

        // 迭代每一个段落
        for (XWPFParagraph xwpfParagraph : xwpfParagraphs) {

            // 原文档有多少个段落 我就创建多少个
            XWPFParagraph wordOutputParagraph = wordOutput.createParagraph();

            // 获取当前段落的所有run
            List<XWPFRun> runs = xwpfParagraph.getRuns();

            for (XWPFRun run : runs) {
                XWPFRun wordOutputParagraphRun = wordOutputParagraph.createRun();
                // 赋值
                //wordOutputParagraphRun.setText("哈哈哈哈~我修改过了");
                // 添加回车 硬回车
                //wordOutputParagraphRun.addCarriageReturn();
                //wordOutputParagraphRun.addBreak(); // 软回车
                wordOutputParagraphRun.setText(run.getText(run.getCharacterSpacing()));
            }

        }

        // 获取所有表格
        List<XWPFTable> xwpfTables = wordInput.getTables();
        for (XWPFTable xwpfTable : xwpfTables) {
            XWPFTable wordOutputTable = wordOutput.createTable();
            // 获取一个表格中的所有行
            List<XWPFTableRow> xwpfTableRows = xwpfTable.getRows();
            System.out.println("xwpfTableRows个数"+xwpfTableRows.size());
            for (XWPFTableRow xwpfTableRow : xwpfTableRows) {

                XWPFTableRow wordOutputTableRow = wordOutputTable.createRow();
                // 获取一行的所有列
                List<XWPFTableCell> xwpfTableCell = xwpfTableRow.getTableCells();
                System.out.println("xwpfTableCell个数"+xwpfTableCell.size());
                int index = 0;
                for (XWPFTableCell tableCell : xwpfTableCell) {
                    index++;
                    XWPFTableCell wordOutputTableRowCell = wordOutputTableRow.createCell();
                    // 获取单个列
                    //wordOutputTableRowCell.setText("哈哈哈哈~我修改过了");
                    System.out.println(tableCell.getText());
                    wordOutputTableRowCell.setText(tableCell.getText());
                    System.out.println("index:"+index);
                }

            wordOutputTable.removeRow(0);
            }
            //wordOutputTable.removeBorders(); 虚线边框

        }

        CTDocument1 document = wordInput.getDocument();
        System.out.println();


        wordOutput.write(fileOutputStream);
        wordInput.close();
        wordOutput.close();
        inputStream.close();
        fileOutputStream.close();
    }

}

  

获取文档中的所有图片代码

private void getPictureImage(String filepath) throws IOException {
        XWPFDocument doc = new XWPFDocument(new FileInputStream(filepath));



        List<ImageInfo> result = Lists.newArrayList();
        Pattern pattern = Pattern.compile(PICTURE_IMG_PATTERN);
        for (XWPFParagraph paragraph : doc.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                System.out.println("............................." + paragraph.getRuns());
                for (XWPFPicture embeddedPicture : run.getEmbeddedPictures()) {
                    System.out.println("............................." + embeddedPicture.getDescription());
                    Matcher matcher = pattern.matcher(embeddedPicture.getDescription());
                    while (matcher.find()) {
                        String source = matcher.group();
                        ImageInfo imageInfo = new ImageInfo();
                        imageInfo.setSource(source);
                        imageInfo.setImageField(getImageField(imageInfo.getSource()));
                        imageInfo.setFiled(getField(imageInfo.getSource()));
                        result.add(imageInfo);
                    }
                }
            }
        }


        List<XWPFTable> xwpfTables = doc.getTables();
        for (XWPFTable xwpfTable : xwpfTables) {
            List<XWPFTableRow> xwpfTableRows = xwpfTable.getRows();
            for (XWPFTableRow xwpfTableRow : xwpfTableRows) {
                List<XWPFTableCell> xwpfTableCells = xwpfTableRow.getTableCells();
                for (XWPFTableCell xwpfTableCell : xwpfTableCells) {
                    for (XWPFParagraph paragraph : xwpfTableCell.getParagraphs()) {
                        for (XWPFRun run : paragraph.getRuns()) {
                            for (XWPFPicture embeddedPicture : run.getEmbeddedPictures()) {
                                Matcher matcher = pattern.matcher(embeddedPicture.getDescription());
                                while (matcher.find()) {
                                    String source = matcher.group();
                                    ImageInfo imageInfo = new ImageInfo();
                                    imageInfo.setSource(source);
                                    imageInfo.setImageField(getImageField(imageInfo.getSource()));
                                    imageInfo.setFiled(getField(imageInfo.getSource()));
                                    result.add(imageInfo);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

  

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

原文链接:https://blog.csdn.net/weixin_43702146/article/details/116159448

 

标签:word,表格,imageInfo,List,XWPFDocument,获取,文档,poi
From: https://www.cnblogs.com/abel-he/p/18192089

相关文章

  • NPOI读取模板文件生成Excel
    前不久实现了用NPOI组件替代Microsoft.Office.Interop.Excel原生组件实现导出数据到Excel的需求,其中踩了几个坑,这里记录一下。不能使用wps创建模板文件不能使用一个文件流,对已存在Excel文件进行修改NPOI中sheet、row、cell都是以0作为起始序号,Office原生组件是以1作为起始序......
  • 用手机免费pdf转word文档怎么操作?
    众所周知,PDF是不可直接编辑的文件,尤其是扫描件。如果要将pdf文件转换为word文件,如何进行转换?其实我们可以通过工具把pdf转word文档的操作哦。有很多人不知道用什么工具好,小编今天就给大家推荐一款手机也能免费将pdf文档转成word文档的在线工具smallpdf中文版。pdf转word可以在线......
  • The 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. T
    numba无法支持nopython错误解决错误:The'nopython'keywordargumentwasnotsuppliedtothe'numba.jit'decorator.TheimplicitdefaultvalueforthisargumentiscurrentlyFalse,butitwillbechangedtoTrueinNumba0.59.0.Seehttps://numb......
  • mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_pa
    今天将程序部署到服务器,遇到mysql.connector.errors.NotSupportedError:Authenticationplugin'caching_sha2_password'isnotsupported问题产生的原因:从MySQL8.0开始,默认的用户认证插件从mysql_native_password变成了caching_sha2_password查看现有的用户mysql>se......
  • 洛谷P3556 [POI2013] MOR-Tales of seafaring的三种解法
    本题模板为奇偶最短路(边权为1时的),题目链接:https://www.luogu.com.cn/problem/P3556为了研究,码了三种不同最短路解放的奇偶做法,便于不同群体理解.一:BFS,对于边权为1,求最短路当然是BFS最快了,时间复杂度:o(nm),代码如下:点击查看代码//背景:我的BFS奇偶最短路尝试//思......
  • checkpoint防火墙测试授权申请
    本文介绍如何在线申请checkpoint防火墙的测试授权请先确保已注册官网账号并能正常登录ProductCenter,并安装好checkpoint并配置好管理IP(授权申请需要用到设备IP地址,不需要连网)(官网账号最好使用公司邮箱申请)ProductCenter链接正常登录后可看到如下图内容其中selecta......
  • SystemVerilog -- 10.2 SystemVerilog Coverpoint Bins
    SystemVerilogCoverpointBins该构造允许在coverpoint变量的给定可能值范围内为每个值创建一个单独的bin。binUsagecoverpointmode{//Manuallycreateaseparatebinforeachvaluebinszero={0};binsone={1};//AllowSystemVerilogtoautomatic......
  • Webshell流量分析之菜刀Chopper&蚁剑AntSword
    目录中国菜刀蚁剑菜刀和蚁剑的一句话木马的流量都有一个特点,都没有加密的,使用wireshark抓包来分析。中国菜刀中国菜刀是一款经典的webshell管理工具,具有文件管理、数据库管理、虚拟终端等功能。这里以菜刀2016为例。在服务器准备php一句话木马:<?php@eval($_POST['pass']);?>......
  • SystemVerilog -- 10.1 SystemVerilog Covergroup and Coverpoint
    SystemVerilogCovergroupandCoverpointSystemVerilog是一种用户定义的类型,用于封装覆盖率模型的规范。它们可以定义一次,并通过函数在不同位置实例化多次。covergroupnewcovergroup可以在包、模块、程序、接口类中定义,通常封装以下信息:AsetofcoveragepointsCrosscov......
  • Script of Narrative Writing from different point of view
    Frozen​Elsa'sperspective​I'mElsa,aprincess,andIhaveasisternamedAnna.Ihavethemagictocontroltheiceandsnow.However,duringaplaywithmysister,Iaccidentallyhurtherwithmagic.Myparentstookustoaskthetrollsforhel......