[英]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.