要在此代码中支持复制行图片,你需要进行以下修改:
- 导入POI的相关类:
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Drawing;
- 在
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);
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<?> drawingPatriarchSource = ((Sheet)source.getSheet()).createDrawingPatriarch();
Drawing<?> drawingPatriarchTarget = ((Sheet)target.getSheet()).createDrawingPatriarch();
if (drawingPatriarchSource != null && drawingPatriarchTarget != null) {
for (Picture picture : drawingPatriarchSource.getPictures()) {
if (picture.getRow() == source.getRowIndex()) {
int pictureIndex = workbook.addPicture(picture.getData(), picture.getPictureType());
ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor();
anchor.setCol1(picture.getClientAnchor().getCol1());
anchor.setCol2(picture.getClientAnchor().getCol2());
anchor.setRow1(target.getRowNum());
anchor.setRow2(target.getRowNum());
PictureData pictureData = workbook.getAllPictures().get(pictureIndex - 1);
drawingPatriarchTarget.createPicture(anchor, pictureIndex).resize();
}
}
}
}
}
}
这样,copyRow()
方法会复制源行的图片到目标行。
请注意,要确保原始工作簿中已经存在足够的空间来容纳复制的图片,否则可能会发生错误。
内容由零声教学AI助手提供,问题来源于学员提问