要支持复制行图片,你需要在copyRow方法中添加一些额外的逻辑。以下是修改后的代码示例:
private void copyRow(Row source, Row target, Workbook workbook) {
// 遍历源行的每个单元格
for (int i = source.getFirstCellNum(); i <= source.getLastCellNum(); i++) {
Cell sourceCell = source.getCell(i);
// 如果源单元格为null,则不创建新单元格
if (sourceCell != null) {
Cell targetCell = target.createCell(i, sourceCell.getCellType());
// 复制单元格样式(包括图片)
CellStyle sourceCellStyle = sourceCell.getCellStyle();
CellStyle targetCellStyle = workbook.createCellStyle();
targetCellStyle.cloneStyleFrom(sourceCellStyle);
// 复制图像(如果有)
if (sourceCell.getCellType() == CellType.PICTURE) {
List<? extends PictureData> pictures = workbook.getAllPictures();
if (!pictures.isEmpty()) {
CreationHelper creationHelper = workbook.getCreationHelper();
Drawing<?> drawingPatriarch = targetSheet.createDrawingPatriarch();
for (PictureData picture : pictures) {
int pictureIndex = workbook.addPicture(picture.getData(), picture.getPictureType());
ClientAnchor anchor = creationHelper.createClientAnchor();
anchor.setCol1(sourceCell.getColumnIndex());
anchor.setCol2(sourceCell.getColumnIndex() + 1);
anchor.setRow1(source.getRowNum());
anchor.setRow2(source.getRowNum() + 1);
drawingPatriarch.createPicture(anchor, pictureIndex);
}
}
}
targetCell.setCellStyle(targetCellStyle);
// 根据单元格类型复制值
switch (sourceCell.getCellTypeEnum()) {
case STRING:
targetCell.setCellValue(sourceCell.getStringCellValue());
break;
case NUMERIC:
targetCell.setCellValue(sourceCell.getNumericCellValue());
break;
case BOOLEAN:
targetCell.setCellValue(sourceCell.getBooleanCellValue());
break;
case FORMULA:
// 如果单元格是公式,则复制公式本身
targetCell.setCellFormula(sourceCell.getCellFormula());
break;
case BLANK:
// target.setCellType(CellType.BLANK);
break;
default:
// 默认处理
}
}
}
}
上述代码会在copyRow方法中添加了复制图片的逻辑,当源单元格包含图片时,它将被复制到目标单元格中。请确保你已经正确设置了图片相关的依赖库和引入语句。
内容由零声教学AI助手提供,问题来源于学员提问




