要支持复制行图片,需要对代码进行以下修改:
添加依赖库:在项目中添加 Apache POI-OOXML 库,以便处理带有图像的单元格。
在 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.setBlank();
break;
default:
// 默认处理
}
// 复制图像(如果有)
Drawing<?> drawing = sheet.createDrawingPatriarch();
List<XSSFShape> shapes = ((XSSFDrawing) drawing).getShapes();
for (XSSFShape shape : shapes) {
if (shape instanceof XSSFPicture) {
XSSFPicture picture = (XSSFPicture) shape;
XSSFClientAnchor anchor = picture.getClientAnchor();
if (anchor.getRow1() == source.getRowNum()) {
int dx1 = anchor.getDx1();
int dy1 = anchor.getDy1();
int dx2 = anchor.getDx2();
int dy2 = anchor.getDy2();
ClientAnchor newAnchor = workbook.getCreationHelper().createClientAnchor();
newAnchor.setCol1(anchor.getCol1());
newAnchor.setRow1(target.getRowNum());
newAnchor.setDx1(dx1);
newAnchor.setDy1(dy1);
newAnchor.setDx2(dx2);
newAnchor.setDy2(dy2);
PictureData pictureData = picture.getPictureData();
int pictureIndex = workbook.addPicture(pictureData.getData(), Workbook.PICTURE_TYPE_PNG);
Drawing<?> targetDrawing = targetSheet.createDrawingPatriarch();
Picture targetPicture = targetDrawing.createPicture(newAnchor, pictureIndex);
内容由零声教学AI助手提供,问题来源于学员提问