问题
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