要支持复制图片类型,您可以使用Picture
类来处理单元格中的图片。以下是修改后的代码示例:
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:
// 处理空白单元格
break;
default:
// 默认处理
}
// 复制图片(如果有)
if (sourceWorkbook instanceof XSSFWorkbook && targetWorkbook instanceof XSSFWorkbook) {
XSSFDrawing drawing = ((XSSFSheet)sourceSheet).createDrawingPatriarch();
if (drawing != null) {
List<XSSFShape> shapes = drawing.getShapes();
for (XSSFShape shape : shapes) {
if (shape instanceof XSSFPicture) {
XSSFPicture sourcePicture = (XSSFPicture)shape;
XSSFWorkbook sourceWorkbook = (XSSFWorkbook)source.getCell(0).getSheet().getWorkbook();
XSSFPictureData pictureData = sourcePicture.getPictureData();
// 创建新的图片对象,并将其添加到目标工作簿中
int pictureIdx = targetWorkbook.addPicture(pictureData.getData(), pictureData.getPictureType());
CreationHelper helper = targetWorkbook.getCreationHelper();
Drawing targetDrawing = targetCell.getSheet().createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
// 设置图片位置和大小
anchor.setCol1(targetCell.getColumnIndex());
anchor.setRow1(targetCell.getRowIndex());
anchor.setCol2(targetCell.getColumnIndex() + 1);
anchor.setRow2(targetCell.getRowIndex() + 1);
// 将图片插入到目标单元格中
Picture targetPicture = targetDrawing.createPicture(anchor, pictureIdx);
targetPicture.resize();
}
}
}
}
}
}
}
请注意,这仅适用于使用Apache POI库进行Excel操作,并且仅在源文件和目标文件都是XLSX格式时有效。
内容由零声教学AI助手提供,问题来源于学员提问