java excel 逐行读取,从Excel表单逐行读取图像

在Java中读取包含员工信息和照片的Excel表格时,遇到问题:图片未能正确映射到对应的用户。解决方法是通过形状的锚点确定图片与单元格的关联,从而正确更新用户管理系统中的员工照片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have stuck up in reading images from an Excel sheet.

I have one Excel sheet which includes employee information like name, address and photo of an employee. I want to read it using Java and store it into some user management system.

Following is my code:

int idColumn = ...;

POIFSFileSystem poifs = ...;

HSSFWorkbook workbook = new HSSFWorkbook(poifs);

HSSFSheet sheet = workbook.getSheetAt(0);

List 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());

}

The problem is it's not mapping to the exact user as on Excel sheet:

Suppose user A has image A on excel sheet. But it's not mapping to the user A. So I would like to know the read images row wise.

解决方案

As you might have noticed: a cell in Excel does never contain a Picture (or any other Shape). Instead there is a separate layer that contains all Shape objects for a sheet. Thats why you can place an image across multiple cells.

But you could use the anchor of a shape to determine to which cell it was attached during positioning:

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());

}

}

}

}

}

I'm using the HSSFPatriarch in my example, as this makes it possible to determine the pictures per sheet (if you've got more than one sheet in the file).

It's important to notice that the anchor of a shape doesn't need to be in the cell where the picture is visually positioned - although usually it is. In that case you could extract the position from the dx1 and dy1 attributes of the anchor.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值