要支持复制图片类型,您需要在 copyRow
方法中添加处理图片的逻辑。可以使用 Apache POI 提供的 Drawing
类和 Picture
类来处理图像数据。
首先,在方法开始部分引入相应的类:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPicture;
然后,在 copyRow
方法中添加处理图片的代码块,如下所示:
private void copyRow(Row source, Row target, Workbook workbook) {
Drawing<?> sourceDrawing = ((XSSFSheet) source.getSheet()).createDrawingPatriarch();
Drawing<?> targetDrawing = ((XSSFSheet) target.getSheet()).createDrawingPatriarch();
// 遍历源行的每个单元格
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:
// 默认处理
}
if (sourceDrawing != null && sourceDrawing instanceof XSSFDrawing) {
XSSFDrawing xssfDrawing = (XSSFDrawing) sourceDrawing;
List<XSSFShape> shapes = xssfDrawing.getShapes();
for (XSSFShape shape : shapes) {
if (shape instanceof XSSFPicture) {
XSSFPicture xssfPicture = (XSSFPicture) shape;
XSSFWorkbook xssfWorkbook = (XSSFWorkbook) workbook;
CTPicture ctPicture = xssfPicture.getCTPicture();
byte[] pictureData = ctPicture.getBlipFill().getBlip().getEmbeddedPic().getPicLocks().getNoGrp();
int pictureIndex = xssfWorkbook.addPicture(pictureData, Workbook.PICTURE_TYPE_PNG);
CreationHelper helper = workbook.getCreationHelper();
Drawing<?> targetSheetPatriarch = ((XSSFSheet) target.getSheet()).createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(targetCell.getColumnIndex());
anchor.setRow1(target.getRowNum());
Picture picture = targetSheetPatriarch.createPicture(anchor, pictureIndex);
picture.resize(0.5); // 调整图片大小(可根据需求进行调整)
}
}
}
}
}
}
这样,您可以在 mergeFileSheet
方法中调用 copyRow
方法来复制包含图片的行,以实现复制图片类型的支持。
内容由零声教学AI助手提供,问题来源于学员提问