我一直坚持从 Excel 工作表中读取图像。
我有一张 Excel 工作表,其中包含员工信息,例如员工的姓名、地址和照片。我想使用 Java 读取它并将其存储到某个用户管理系统中。
以下是我的代码:
int idColumn = ...;
POIFSFileSystem poifs = ...;
HSSFWorkbook workbook = new HSSFWorkbook(poifs);
HSSFSheet sheet = workbook.getSheetAt(0);
List<HSSFPictureData> pictures = workbook.getAllPictures();
for (int i = 0; i < pictures.size(); i++) {
HSSFPictureData picture = pictures.get(i);
// This does not map to the row from the picture:
HSSFRowrow = sheet.getRow(i);
HSSFCell idCell = row.getCell(idColumn);
long employeeId = idCell != null ? (long) idCell.getNumericCellValue() : 0;
myUserService.updatePortrait(employeeId, picture.getData());
}
问题是它没有像 Excel 工作表上那样映射到确切的用户: 假设用户A在Excel工作表上有图像A。但它没有映射到用户A。所以我想知道按行读取的图像。
最佳答案
您可能已经注意到:Excel 中的单元格从不包含图片
(或任何其他形状
)。相反,有一个单独的图层,其中包含工作表的所有 Shape
对象。这就是为什么您可以将图像放置在多个单元格中。
但是您可以使用形状的 anchor 来确定它在定位过程中附加到哪个单元格:
int idColumn = ...;
int pictureColumn = ...;
HSSFSheet sheet = ...;
for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {
if (shape instanceof HSSFPicture) {
HSSFPicture picture = (HSSFPicture) shape;
HSSFClientAnchor anchor = (HSSFClientAnchor) picture.getAnchor();
// Ensure to use only relevant pictures
if (anchor.getCol1() == pictureColumn) {
// Use the row from the anchor
HSSFRow pictureRow = sheet.getRow(anchor.getRow1());
if (pictureRow != null) {
HSSFCell idCell = pictureRow.getCell(idColumn);
if (idCell != null) {
long employeeId = (long) idCell.getNumericCellValue();
myUserService.updatePortrait(employeeId, picture.getData());
}
}
}
}
}
在我的示例中,我使用 HSSFPatriarch
,因为这样可以确定每张纸上的图片(如果您的文件中有不止一张纸)文件)。
需要注意的是,形状的 anchor 不需要位于图片视觉定位的单元格中 - 尽管通常是这样。在这种情况下,您可以从 anchor 的 dx1 和 dy1 属性中提取位置。
关于java - 逐行读取 Excel 工作表中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33030908/