从Word文档中提取表格:使用Apache POI库

3

主线程中的异常:org.apache.poi.poifs.filesystem.OfficeXmlFileException: 提供的数据似乎是Office 2007 + XML格式。POI仅支持OLE2 Office文件 at org.apache.poi.poifs.storage.HeaderBlockReader.(HeaderBlockReader.java:96) at org.apache.poi.poifs.filesystem.POIFSFileSystem.(POIFSFileSystem.java:84) at com.TableTest.main(TableTest.java:19)

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
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.TableRow;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class TableTest {

    public static void main(String args[]) throws IOException
    {
//        String fileName="D:\\New folder\\Annual.doc";

        InputStream fis=new FileInputStream("D://New folder//Annual.docx");
        POIFSFileSystem fs=new POIFSFileSystem(fis);
        HWPFDocument doc=new HWPFDocument(fs);

        Range range=doc.getRange();

        for(int i=0;i<range.numParagraphs();i++)
        {
            Paragraph par=range.getParagraph(i);
            System.out.println(par.text());
        }
        Paragraph tablePar=range.getParagraph(0);
        if(tablePar.isInTable())
        {
            Table table=range.getTable(tablePar);
            for(int rowIdx=0;rowIdx<table.numRows();rowIdx++)
            {
                TableRow row=table.getRow(rowIdx);
                System.out.println("row "+(rowIdx+1)+",is table header: "+row.isTableHeader());
                for(int colIdx=0;colIdx<row.numCells();colIdx++)
                {
                    TableCell cell=row.getCell(colIdx);
                    System.out.println("column "+(colIdx+1)+",text= "+cell.getParagraph(0).text());
                }
            }
        }
    }

}
1个回答

0

HWPF 适用于基于 OLE2 的 .doc 文件。对于 .docx 文件,您需要使用 XWPF。

尝试使用 XWPFDocument

XWPFDocument doc=new XWPFDocument(fs);

1
XWPFDocument doc = new XWPFDocument(OPCPackage.open(fis)); Range range = doc.getRange(); // 报错 - Osama Hashem
@Osama Hashem 你遇到了什么错误? - Andrey E

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接