我正在尝试使用方法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[]
。