要支持复制行图片,您需要对代码进行以下修改:
- 首先,在
copyRow方法中,添加处理复制行图片的逻辑。可以使用Drawing对象来获取源行的图片,并将其复制到目标行上。示例代码如下:
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);
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:
// 默认处理
}
// 复制行图片
Drawing<?> drawing = ((XSSFSheet)source.getSheet()).createDrawingPatriarch();
List<XSSFShape> shapes = ((XSSFDrawing)drawing).getShapes();
for (XSSFShape shape : shapes) {
if (shape instanceof XSSFPicture) {
XSSFPicture sourcePicture = (XSSFPicture) shape;
XSSFClientAnchor anchor = sourcePicture.getClientAnchor();
if (anchor.getRow1() == source.getRowNum()) { // 图片所在行与源行一致
int colIndex = anchor.getCol1();
int rowIndex = target.getRowNum(); // 目标行的索引
XSSFDrawing targetDrawing = ((XSSFSheet)target.getSheet()).createDrawingPatriarch();
XSSFClientAnchor targetAnchor = new XSSFClientAnchor(anchor.getDx1(), anchor.getDy1(),
anchor.getDx2(), anchor.getDy2(), colIndex, rowIndex, colIndex, rowIndex);
Picture targetPicture = targetDrawing.createPicture(targetAnchor,
workbook.addPicture(sourcePicture.getPictureData().getData(),
sourcePicture.getPictureData().getFormat()));
targetPicture.resize(); // 调整图片大小
}
}
}
}
}
}
- 在
mergeFileSheet方法中调用copyRow时,将复制源行及其图片到目标行上。示例代码如下:
...
for (Row sourceRow : attachmentSheet) {
Row targetRow = newSheet.createRow(sourceRow.getRowNum());
// 复制附件及图片
copyRow(sourceRow, targetRow, originalWorkbook);
}
...
通过以上修改,您可以实现将源行的内容、样式以及图片复制到目标行的功能。
内容由零声教学AI助手提供,问题来源于学员提问




