Java中如何从XSSFSheet移除Excel图片?
How to Properly Remove Images from XSSFSheet in Apache POI
I totally get your frustration—Apache POI’s documentation is surprisingly sparse on this specific operation, and workarounds like copying everything to a new sheet feel clunky at best. You’re right that the key lies in cleaning up the association within XSSFDrawing—here’s how to do it properly:
Step-by-Step Solution
The core issue with your earlier attempts (negative row anchors, etc.) is that they only hide the image, not remove its underlying data from the Excel file. To fully delete an image, you need to remove it from both the drawing’s shape list and the underlying XML structure.
Here’s a working code example:
// Get your target sheet XSSFSheet sheet = workbook.getSheetAt(0); XSSFDrawing drawing = sheet.getDrawingPatriarch(); if (drawing != null) { // Iterate backwards to avoid index shifting issues when removing items List<XSSFShape> shapes = drawing.getShapes(); for (int i = shapes.size() - 1; i >= 0; i--) { XSSFShape shape = shapes.get(i); if (shape instanceof XSSFPicture) { XSSFPicture picture = (XSSFPicture) shape; // Add your custom condition here to target the specific image // For example: check anchor position, picture data index, etc. // if (picture.getAnchor().getRow1() == targetRow) { // Remove the shape from the drawing's in-memory list shapes.remove(i); // Clean up the underlying XML to avoid Excel repair prompts drawing.getCTDrawing().removeObject(i); // } } } }
Why This Works
getDrawingPatriarch()gives you access to all drawing objects (including images) on the sheet.- Iterating in reverse prevents index errors when you remove shapes from the list.
- Calling
removeObject(i)on theCTDrawingobject ensures the image’s XML data is fully deleted from the file, not just hidden—this is why your negative anchor trick caused repair prompts (the invalid anchor was still present in the XML).
Notes
- Make sure to add a condition to target the exact image you want to delete (e.g., check its anchor position, or compare picture data if you have a reference to it). Without this, the code will remove all images from the sheet.
- This works for most recent Apache POI versions (4.x and 5.x). If you’re on an older version, the
CTDrawingmethod names might vary slightly, but the core logic remains the same.
内容的提问来源于stack exchange,提问作者kscherrer
相关产品推荐
相关产品推荐

