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

回眸只為那壹抹淺笑 提交于 2020-01-16 18:42:09

问题


I am trying to read images from xl_sheet using method wbook.getAllpicture(); but I found that these images are returning as whole I can not keep images separated according workshets.


回答1:


In Excel the pictures data are stored on Workbook level. This is what Workbook.getAllPictures actually gets.

Each sheet has a Drawing layer which hovers over the sheet. In this Drawing are Shapes which are anchored to the sheet and may also be linked to the pictures data stored on Workbook level. If so, the shape does showing that picture.

So for getting the pictures dependent of the sheets, we must run over the appropriate Drawing layer, determining whether the shape we found is linked to a picture. If so, we get that picture.

Example:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import java.io.FileInputStream;

class ExcelGetXSSFPicturesWithPosition {

 public static void main(String[] args) throws Exception {

  Workbook workbook = WorkbookFactory.create(new FileInputStream("ExcelWithImages.xlsx"));

  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
 );

     }
    }
   }
  }

  workbook.close();
 }
}

For getting the picture data out of the XSSFPicture we can use XSSFPicture.getPictureData.



来源:https://stackoverflow.com/questions/49206214/apache-poi-images-in-spreadsheet-are-associated-with-workbook-and-can-not-be-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!