Apache POI:电子表格中的图像与工作簿相关联,无法检索/链接到单个工作表



我正在尝试使用方法wbook.getAllpicture((从xl_sheet读取图像;但我发现这些图像正在整体返回,我无法根据工作将图像分开。

Excel图片数据存储在Workbook级别。这就是Workbook.getAllPictures实际得到的。

每个工作表都有一个悬停在工作表上的Drawing图层。在此Drawing中,Shapes锚定到工作表上,也可以链接到存储在Workbook级别的图片数据。如果是这样,则形状会显示该图片。

因此,为了使图片依赖于工作表,我们必须在适当的Drawing图层上运行,确定我们找到的形状是否链接到图片。如果是这样,我们得到了那张照片。

例:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import java.io.FileInputStream;
class ExcelGetXSSFPicturesWithPosition {
 public static void main(String[] args) throws Exception {
  Workbook workbook = WorkbookFactory.create(new FileInputStream("ExcelWithImages.xlsx"));
  //Workbook workbook = WorkbookFactory.create(new FileInputStream("ExcelWithImages.xls"));
  for (Sheet sheet : workbook) {
   String sheetname = sheet.getSheetName();
   Drawing drawing = sheet.getDrawingPatriarch();
   if (drawing instanceof XSSFDrawing) {
    for (XSSFShape shape : ((XSSFDrawing)drawing).getShapes()) {
     if (shape instanceof XSSFPicture) {
      XSSFPicture xssfPicture = (XSSFPicture)shape;
      String shapename = xssfPicture.getShapeName();
      int row = xssfPicture.getClientAnchor().getRow1();
      int col = xssfPicture.getClientAnchor().getCol1();
System.out.println(
 "Picture with Shapename: " + shapename + 
 " is located sheet: " + sheetname + 
 ", row: " + row + 
 ", col: " + col
 );
     }
    }
   } else if (drawing instanceof HSSFPatriarch) {
    for (HSSFShape shape : ((HSSFPatriarch)drawing).getChildren()) {
     if (shape instanceof HSSFPicture) {
      HSSFPicture hssfPicture = (HSSFPicture)shape;
      String shapename = hssfPicture.getShapeName();
      int row = hssfPicture.getClientAnchor().getRow1();
      int col = hssfPicture.getClientAnchor().getCol1();
System.out.println(
 "Picture with Shapename: " + shapename + 
 " is located sheet: " + sheetname + 
 ", row: " + row + 
 ", col: " + col
 );
     }
    }
   }
  }
  workbook.close();
 }
}

为了从XSSFPicture中获取图片数据,我们可以使用 XSSFPicture.getPictureData。对于HSSFPicture,我们可以使用HSSFPicture.getPictureData。

两者都提供了PictureData.getData,它返回一个包含图片二进制数据的byte[]

最新更新