从Excel表格中逐行读取图像

我从一张Excel表格读取图像。

我有一个Excel工作表,其中包括员工信息,如员工的姓名,地址和照片。 我想用Java读取它并将其存储到某个用户pipe理系统中。

以下是我的代码:

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中的单元格从不包含 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 ,因为这样可以确定每张图片的图片(如果你在文件中有多张图片)。

重要的是要注意,形状的锚不需要在图片被视觉定位的单元中 – 虽然通常是这样。 在这种情况下,您可以从锚的dx1dy1属性中提取位置。

 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++; } } }