Java 如何从.docx文件中提取数据,包括图像、表格、公式等?

Java 如何从.docx文件中提取数据,包括图像、表格、公式等?,java,ms-word,apache-poi,Java,Ms Word,Apache Poi,我正在做一项任务,我必须从word文档中提取数据,主要是图像、表格和特殊文本(公式等) 我能够保存word文件中的图像,它是从web下载的,但当我将相同的代码应用到.docx文件时,它会给出错误 相同的代码是 //create file inputstream to read from a binary file FileInputStream fs=new FileInputStream(filename); //create office word 2007+ doc

我正在做一项任务,我必须从word文档中提取数据,主要是图像、表格和特殊文本(公式等)

我能够保存word文件中的图像,它是从web下载的,但当我将相同的代码应用到.docx文件时,它会给出错误

相同的代码是

//create file inputstream to read from a binary file
      FileInputStream fs=new FileInputStream(filename);
      //create office word 2007+ document object to wrap the word file
      XWPFDocument docx=new XWPFDocument(fs);
      //get all images from the document and store them in the list piclist
      List<XWPFPictureData> piclist=docx.getAllPictures();
      //traverse through the list and write each image to a file
      Iterator<XWPFPictureData> iterator=piclist.iterator();
      System.out.println(piclist.size());
      while(iterator.hasNext()){

       XWPFPictureData pic=iterator.next();
       byte[] bytepic=pic.getData();
       int i=0;
       BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytepic));
       //captureimage(imag,i,flag,j);
       if(imag != null)
       {
               ImageIO.write(imag, "jpg", new File("D:/imagefromword"+i+".jpg"));  
       }else{
           System.out.println("imag is empty");
       }
//创建要从二进制文件读取的文件inputstream
FileInputStream fs=新的FileInputStream(文件名);
//创建office word 2007+文档对象以包装word文件
XWPFDocument docx=新XWPFDocument(fs);
//从文档中获取所有图像并将其存储在列表中
List piclist=docx.getAllPictures();
//遍历列表并将每个图像写入文件
迭代器迭代器=piclist.Iterator();
System.out.println(piclist.size());
while(iterator.hasNext()){
xwpfpicturedatapic=iterator.next();
byte[]bytepic=pic.getData();
int i=0;
BuffereImage imag=ImageIO.read(新的ByteArrayInputStream(bytepic));
//captureimage(图像,i,标志,j);
如果(imag!=null)
{
write(imag,“jpg”,新文件(“D:/imagefromword“+i+”.jpg”);
}否则{
System.out.println(“imag为空”);
}
它给出了不正确的格式错误。但我无法更改文档文件。 其次,对于上面的代码,如果我有一个以上的图像,并且当我保存这个图像时,比每次保存图像时都要多。假设我们有3个图像,那么它将保存3个图像,但所有三个都是最新的图像


任何帮助都将不胜感激。

没有实际错误,只能猜测。 但是有两种POI实现HWPF和XWPF,这取决于您读取的word文档版本是旧文档版本还是xml新文档版本。通常,当您尝试使用错误的文档打开文档时,会出现格式错误。
此外,您还需要完整的poi ooxml模式jar来读取更复杂的文档。

请根据错误添加stacktrace。