簡體   English   中英

apache poi:電子表格中的圖像與工作簿相關聯,無法與單個工作表檢索/鏈接..

[英]apache poi: images in spreadsheet are associated with workbook and can not be retrieved/linked with individual worksheet ..

我正在嘗試使用 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我們可以使用HSFSFPicture.getPictureData

這兩者都提供了PictureData.getData ,它返回一個包含圖片二進制數據的byte[]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM