要复制源sheet行中的图片,你需要进行以下修改:
- 在导入所需的类之后,引入POI的
XSSFDrawing和XSSFClientAnchor类:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
// ...
- 在创建新的sheet页之前,获取原始Workbook的CreationHelper对象,并在创建新行时为它创建Drawing对象:
// 获取原始Workbook的CreationHelper对象
CreationHelper creationHelper = originalWorkbook.getCreationHelper();
int sheetIndex = 0;
for (int i = 0; i < numberOfSheets; i++) {
// ...
// 创建新的sheet页来放置附件内容
Sheet newSheet = originalWorkbook.createSheet(newSheetName);
// 为新行创建Drawing对象
Drawing<?> drawing = newSheet.createDrawingPatriarch();
for (Row sourceRow : attachmentSheet) {
Row targetRow = newSheet.createRow(sourceRow.getRowNum());
// ...
}
}
- 在复制每个单元格时,检查该单元格是否包含图片。如果是,则复制图片到目标单元格:
for (Row sourceRow : attachmentSheet) {
Row targetRow = newSheet.createRow(sourceRow.getRowNum());
for (Cell sourceCell : sourceRow) {
Cell targetCell = targetRow.createCell(sourceCell.getColumnIndex(), sourceCell.getCellType());
if (sourceCell.getCellType() == CellType.STRING) {
targetCell.setCellValue(sourceCell.getStringCellValue());
} else if (sourceCell.getCellType() == CellType.NUMERIC) {
targetCell.setCellValue(sourceCell.getNumericCellValue());
}
// 复制单元格样式
targetCell.setCellStyle(sourceCell.getCellStyle());
// 检查是否存在图片
XSSFDrawing sourceDrawing = (XSSFDrawing) attachmentSheet.getDrawingPatriarch();
if (sourceDrawing != null) {
for (XSSFShape shape : sourceDrawing.getShapes()) {
if (shape instanceof XSSFPicture) {
XSSFPicture sourcePicture = (XSSFPicture) shape;
XSSFClientAnchor anchor = sourcePicture.getClientAnchor();
if (anchor.getRow1() == sourceRow.getRowNum() && anchor.getCol1() == sourceCell.getColumnIndex()) {
int pictureIndex = originalWorkbook.addPicture(sourcePicture.getPictureData().getData(), Workbook.PICTURE_TYPE_PNG);
CreationHelper helper = originalWorkbook.getCreationHelper();
Drawing<?> targetDrawing = newSheet.createDrawingPatriarch();
ClientAnchor targetAnchor = helper.createClientAnchor();
// 设置目标单元格的锚点位置
targetAnchor.setDx1(anchor.getDx1());
targetAnchor.setDy1(anchor.getDy1());
targetAnchor.setDx2(anchor.getDx2());
targetAnchor.setDy2(anchor.getDy2());
// 设置目标图形的大小和位置
Picture targetPicture = targetDrawing.createPicture(targetAnchor, pictureIndex);
targetPicture.resize();
}
}
}
}
}
}
这样修改后,你就可以复制源sheet行中的图片到新创建的sheet行了。记得在代码最后保存并关闭原始Workbook。
内容由零声教学AI助手提供,问题来源于学员提问




