要支持复制行图片,你可以修改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);
// 复制单元格值
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:
// 直接设置为空白单元格
break;
default:
// 默认处理
}
// 复制单元格中的图片(如果有)
if (source instanceof XSSFSheet && target instanceof XSSFSheet) {
XSSFDrawing sourceDrawing = ((XSSFSheet) source).getDrawingPatriarch();
XSSFDrawing targetDrawing = ((XSSFSheet) target).createDrawingPatriarch();
if (sourceDrawing != null) {
for (XSSFShape shape : sourceDrawing.getShapes()) {
if (shape instanceof XSSFPicture) {
XSSFPicture sourcePicture = (XSSFPicture) shape;
XSSFClientAnchor sourceAnchor = sourcePicture.getClientAnchor();
XSSFClientAnchor targetAnchor = new XSSFClientAnchor(sourceAnchor.getDx1(), sourceAnchor.getDy1(),
sourceAnchor.getDx2(), sourceAnchor.getDy2(),
targetCell.getColumnIndex(), target.getRowNum(), targetCell.getColumnIndex() + 1, target.getRowNum() + 1);
XSSFPicture targetPicture = targetDrawing.createPicture(targetAnchor, workbook.addPicture(sourcePicture.getPictureData().getData(), Workbook.PICTURE_TYPE_PNG));
// 复制图片样式
targetPicture.getCTPicture().getBlipFill().setDpi(sourcePicture.getCTPicture().getBlipFill().getDpi());
}
}
}
}
// 设置复制后的单元格样式
targetCell.setCellStyle(targetCellStyle);
}
}
}
这样,在复制行的同时,会将源行中的图片一并复制到目标行中。请注意,此示例代码假设你使用的是Apache POI库来处理Excel文件,并且Excel文件格式为xlsx(基于XML)而非xls(二进制格式)。
内容由零声教学AI助手提供,问题来源于学员提问




