我一直在阅读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 。所以我想知道读取图像的行。
答案 0 :(得分:3)
您可能已经注意到:Excel中的单元格永远不会包含 Picture
(或任何其他Shape
)。相反,有一个单独的图层包含工作表的所有Shape
个对象。这就是为什么你可以在多个单元格上放置图像的原因。
但您可以使用形状的锚来确定在定位过程中它附着的单元格:
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
,因为这样就可以确定图片每张(如果您有多张图片)文件)。
重要的是要注意到形状的锚点不需要位于图像在视觉上定位的单元格中 - 尽管通常是这样。在这种情况下,您可以从锚点的dx1
和dy1
属性中提取位置。
答案 1 :(得分:-1)
您可以使用以下代码逐行读取Excel工作表中的图像:
POIFSFileSystem poifs = new POIFSFileSystem(fis) ;
HSSFWorkbook workbook = new HSSFWorkbook(poifs);
HSSFSheet sheet = workbook.getSheetAt(0);
int idColumn1 = 14;
int idColumn2 = 16;
int pictureColumn = 0;
//HSSFSheet sheet = null;
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 idCell14 = pictureRow.getCell(17);
HSSFCell idCell16 = pictureRow.getCell(19);
System.out.println(idCell14);
int age = (int)idCell14.getNumericCellValue();
int year = (int)idCell16.getNumericCellValue();
System.out.println(age+":"+year);
HSSFPictureData data = picture.getPictureData();
byte data1[] = data.getData();
FileOutputStream out = new FileOutputStream(age+"."+year+".png");
out.write(data1);
out.close();
pcount++;
}
}
}