POI之Word文档读取-yellowcong

8 篇文章 0 订阅

POI对于Doc的支持冒失对于新版本的Word不支持,支持的是Word老版本,对于docx结尾的,支持不是特别的好,本文主要分三部分,1、Word的文字不分的读取,2、Wrod图片的读取,3、Word表格读取

环境搭建

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

<!-- word -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>3.17</version>
</dependency>

<!-- xlsx -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>
<!-- xlsx  依赖这个包 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.17</version>
</dependency>

文字读取

文字操作中,可以通过HWPFDocument 直接读取,也可以获取到Range对象后读取

String BASE_PATH = "D:\\笔记\\服务器学习\\bae\\";
File file = new File(BASE_PATH + "BAE 服务器文件目录问题.doc");
HWPFDocument doc = new HWPFDocument(new FileInputStream(file));

//通过 Doc对象直接获取Text
StringBuilder sb = doc.getText();
//System.out.println(sb.toString());

//通过Range对象获取Text
Range range = doc.getRange();
String text = range.text();

图片读取

Doc获取文档中的所有图片,并存储,其中Picture 对象中,getContent()可获取字节流,然后获取字节数据,自己写出来,也可以通过writeImageContent 来直接写,图片的开始位置可以获取,但是结束位置没有


//获取doc中的图片数
//获取doc中的图片数
List<Picture> pics = doc.getPicturesTable().getAllPictures();

for(Picture pic:pics){
    //图片在doc文件中的位置,分析Doc 转化成其他文本时需要用到

    int start = pic.getStartOffset();
    int width = pic.getWidth();
    int height = pic.getHeight();
    String mimeType = pic.getMimeType();
    //文件名称
    String name = pic.suggestFullFileName();
    //文件后缀
    String exts= pic.suggestFileExtension();
    //文件类型
    PictureType type = pic.suggestPictureType();
    System.out.printf("开始位置%d\t图片大小度%d,高%d,\t图片类型%s\r\n",start,width,height,mimeType);
}

/**
 * 也可以自己写方法
 * @param imgByte
 * @throws Exception
 */
public static void copyByteToFile(byte[] imgByte,String path) throws Exception {

    InputStream in = new ByteInputStream(imgByte, 0, imgByte.length);
    byte[] buff = new byte[1024];
    String fileName = UUID.randomUUID().toString().substring(0, 6);
    OutputStream out = new FileOutputStream(new File(path + fileName + ".jpg"));

    int len = 0;
    while ((len = in.read(buff)) > 0) {
        out.write(buff, 0, len);
    }

    out.flush();
    out.close();
    in.close();
}

/**
 * 通过Picture 自己类中的读写方法
 * @param pics
 * @param path
 */
public static void copyPic2Disk(List<Picture> pics,File path){
    if(pics == null  || pics.size()  <=0){
        return;
    }
    if(!path.isDirectory()){
        throw new RuntimeException("路径填写不正确");
    }
    //当文件夹路径不存在的情况下,我们自己创建文件夹目录
    if(!path.exists() ){
        path.mkdirs();
    }

    try {
        for(Picture pic:pics){
            //写出数据,我们使用的是Poi类中,Picture自己所带的函数
            pic.writeImageContent(new FileOutputStream(new File(path,pic.suggestFullFileName())));
            /*byte [] picBytes = pic.getContent(); //获取字节流,也可以自己写入数据
            copyByteToFile(picBytes);*/
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Doc的表格读取

//遍历range范围内的table。  
TableIterator tableIter = new TableIterator(range);
while (tableIter.hasNext()) {
    Table table = tableIter.next();
    //开始位置
    int start = table.getStartOffset();
    //结束位置
    int end = table.getEndOffset();
    System.out.printf("开始位置%d,结束为止%d\r\n",start,end);

    //获取行的数目
    int rowNum = table.numRows();
    for (int j = 0; j < rowNum; j++) {
        //获取每一行
        TableRow row = table.getRow(j);
        int cellNum = row.numCells();
        for (int k = 0; k < cellNum; k++) {
            //获取每一列
            TableCell cell = row.getCell(k);
            // 输出单元格的文本
            System.out.println(cell.text().trim());
        }
    }
}

完整代码

package com.yellowcong.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableRow;

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

public class DocText {

    public static void main(String[] args) throws Exception, IOException {
        String BASE_PATH = "D:\\笔记\\服务器学习\\bae\\";
        File file = new File(BASE_PATH + "BAE 服务器文件目录问题.doc");
        HWPFDocument doc = new HWPFDocument(new FileInputStream(file));

        //通过 Doc对象直接获取Text
        StringBuilder sb = doc.getText();
        //System.out.println(sb.toString());

        //通过Range对象获取Text
        Range range = doc.getRange();
        String text = range.text();
        //System.out.println(text);

        //获取段落数目
        //在Word中,一个回车符就是一个段落了
        int nums = range.numParagraphs();
        //System.out.println(nums);

        //获取doc中的图片数
        List<Picture> pics = doc.getPicturesTable().getAllPictures();

        for(Picture pic:pics){
            //图片在doc文件中的位置,分析Doc 转化成其他文本时需要用到
            int start = pic.getStartOffset();
            int width = pic.getWidth();
            int height = pic.getHeight();
            String mimeType = pic.getMimeType();

            System.out.printf("开始位置%d\t图片大小度%d,高%d,\t图片类型%s\r\n",start,width,height,mimeType);
        }
        //1.通过Picture的writeImageContent方法 写文件
        //2.获取Picture的byte 自己写
        copyPic2Disk(pics, new File(BASE_PATH));


        //遍历range范围内的table。  
        TableIterator tableIter = new TableIterator(range);
        while (tableIter.hasNext()) {
            Table table = tableIter.next();
            //开始位置
            int start = table.getStartOffset();
            //结束位置
            int end = table.getEndOffset();
            System.out.printf("开始位置%d,结束为止%d\r\n",start,end);

            //获取行的数目
            int rowNum = table.numRows();
            for (int j = 0; j < rowNum; j++) {
                //获取每一行
                TableRow row = table.getRow(j);
                int cellNum = row.numCells();
                for (int k = 0; k < cellNum; k++) {
                    //获取每一列
                    TableCell cell = row.getCell(k);
                    // 输出单元格的文本
                    System.out.println(cell.text().trim());
                }
            }
        }
    }

    /**
     * 也可以自己写方法
     * @param imgByte
     * @throws Exception
     */
    public static void copyByteToFile(byte[] imgByte,String path) throws Exception {

        InputStream in = new ByteInputStream(imgByte, 0, imgByte.length);
        byte[] buff = new byte[1024];
        String fileName = UUID.randomUUID().toString().substring(0, 6);
        OutputStream out = new FileOutputStream(new File(path + fileName + ".jpg"));

        int len = 0;
        while ((len = in.read(buff)) > 0) {
            out.write(buff, 0, len);
        }

        out.flush();
        out.close();
        in.close();
    }

    /**
     * 通过Picture 自己类中的读写方法
     * @param pics
     * @param path
     */
    public static void copyPic2Disk(List<Picture> pics,File path){
        if(pics == null  || pics.size()  <=0){
            return;
        }
        if(!path.isDirectory()){
            throw new RuntimeException("路径填写不正确");
        }
        //当文件夹路径不存在的情况下,我们自己创建文件夹目录
        if(!path.exists() ){
            path.mkdirs();
        }

        try {
            for(Picture pic:pics){
                //写出数据,我们使用的是Poi类中,Picture自己所带的函数
                pic.writeImageContent(new FileOutputStream(new File(path,pic.suggestFullFileName())));
                /*byte [] picBytes = pic.getContent(); //获取字节流,也可以自己写入数据
                copyByteToFile(picBytes);*/
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

完整代码

package com.yellowcong.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableRow;

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

public class DocText {

    public static void main(String[] args) throws Exception, IOException {
        String BASE_PATH = "D:\\笔记\\服务器学习\\bae\\";
        File file = new File(BASE_PATH + "BAE 服务器文件目录问题.doc");
        HWPFDocument doc = new HWPFDocument(new FileInputStream(file));

        //通过 Doc对象直接获取Text
        StringBuilder sb = doc.getText();
        //System.out.println(sb.toString());

        //通过Range对象获取Text
        Range range = doc.getRange();
        String text = range.text();
        //System.out.println(text);

        //获取段落数目
        //在Word中,一个回车符就是一个段落了
        int nums = range.numParagraphs();
        //System.out.println(nums);

        //获取doc中的图片数
        List<Picture> pics = doc.getPicturesTable().getAllPictures();

        for(Picture pic:pics){
            //图片在doc文件中的位置,分析Doc 转化成其他文本时需要用到
            //文件开始位置,结束位置没有
            int start = pic.getStartOffset();
            //图片的宽高
            int width = pic.getWidth();
            int height = pic.getHeight();

            //文件名称
            String name = pic.suggestFullFileName();
            //文件后缀
            String exts= pic.suggestFileExtension();
            //文件类型
            PictureType type = pic.suggestPictureType();

            String mimeType = pic.getMimeType();

            System.out.printf("开始位置%d\t图片大小度%d,高%d,\t图片类型%s\r\n",start,width,height,mimeType);
        }
        //1.通过Picture的writeImageContent方法 写文件
        //2.获取Picture的byte 自己写
        copyPic2Disk(pics, new File(BASE_PATH));


        //遍历range范围内的table。  
        TableIterator tableIter = new TableIterator(range);
        while (tableIter.hasNext()) {
            Table table = tableIter.next();
            //开始位置
            int start = table.getStartOffset();
            //结束位置
            int end = table.getEndOffset();
            System.out.printf("开始位置%d,结束为止%d\r\n",start,end);

            //获取行的数目
            int rowNum = table.numRows();
            for (int j = 0; j < rowNum; j++) {
                //获取每一行
                TableRow row = table.getRow(j);
                int cellNum = row.numCells();
                for (int k = 0; k < cellNum; k++) {
                    //获取每一列
                    TableCell cell = row.getCell(k);
                    // 输出单元格的文本
                    System.out.println(cell.text().trim());
                }
            }
        }
    }

    /**
     * 也可以自己写方法
     * @param imgByte
     * @throws Exception
     */
    public static void copyByteToFile(byte[] imgByte,String path) throws Exception {

        InputStream in = new ByteInputStream(imgByte, 0, imgByte.length);
        byte[] buff = new byte[1024];
        String fileName = UUID.randomUUID().toString().substring(0, 6);
        OutputStream out = new FileOutputStream(new File(path + fileName + ".jpg"));

        int len = 0;
        while ((len = in.read(buff)) > 0) {
            out.write(buff, 0, len);
        }

        out.flush();
        out.close();
        in.close();
    }

    /**
     * 通过Picture 自己类中的读写方法
     * @param pics
     * @param path
     */
    public static void copyPic2Disk(List<Picture> pics,File path){
        if(pics == null  || pics.size()  <=0){
            return;
        }
        if(!path.isDirectory()){
            throw new RuntimeException("路径填写不正确");
        }
        //当文件夹路径不存在的情况下,我们自己创建文件夹目录
        if(!path.exists() ){
            path.mkdirs();
        }

        try {
            for(Picture pic:pics){
                //写出数据,我们使用的是Poi类中,Picture自己所带的函数
                pic.writeImageContent(new FileOutputStream(new File(path,pic.suggestFullFileName())));
                /*byte [] picBytes = pic.getContent(); //获取字节流,也可以自己写入数据
                copyByteToFile(picBytes);*/
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

狂飙的yellowcong

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

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

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

打赏作者

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

抵扣说明:

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

余额充值