Using OpenXML 3.0.2, everything works fine, the images seems like added into the Excel file (judging by the file size increased), the Excel can be opened and view without any problem. But the image is missing.
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
public static void Test()
{
using var Doc = SpreadsheetDocument.Open("Test.xlsx", true);
var nDoc = Doc.Clone("Test1.xlsx");
var wss = Doc.WorkbookPart!.Workbook
.GetFirstChild<Sheets>()!.Elements<Sheet>().FirstOrDefault()!;
var ws = (WorksheetPart)(Doc.WorkbookPart.GetPartById(wss.Id!.Value!));
DrawingsPart dp = null!;
ImagePart ip = null!;
if (ws.DrawingsPart != null) dp = ws.DrawingsPart;
else dp = ws.AddNewPart<DrawingsPart>();
ip = dp.AddImagePart(ImagePartType.Png);
var img = File.ReadAllBytes("diet.png");
using var ms = new MemoryStream(img);
ip.FeedData(ms);
AddImageToSheet(dp, ip, 2, 2);
nDoc.Save();
}
private static void AddImageToSheet(DrawingsPart drawingsPart, ImagePart imagePart, int col, int row)
{
Bitmap image = new Bitmap(imagePart.GetStream());
long imageWidth = image.Width * 9525; // Convert pixels to EMUs
long imageHeight = image.Height * 9525; // Convert pixels to EMUs
// Assuming standard cell size (adjust as needed)
long cellWidth = 64 * 9525; // 64 pixels
long cellHeight = 20 * 9525; // 20 pixels
// Center image within cell
long offsetX = (cellWidth - imageWidth) / 2;
long offsetY = (cellHeight - imageHeight) / 2;
var nvps = new NonVisualDrawingProperties() { Id = 1025, Name = "Picture 1" };
var nvpicprops = new NonVisualPictureDrawingProperties(new PictureLocks() { NoChangeAspect = true });
var blipFill = new BlipFill(new Blip() { Embed = drawingsPart.GetIdOfPart(imagePart) }, new Stretch(new FillRectangle()));
var shapeProps = new DocumentFormat.OpenXml.Drawing.ShapeProperties(new Transform2D(new Offset() { X = col * cellWidth + offsetX, Y = row * cellHeight + offsetY }, new Extents() { Cx = imageWidth, Cy = imageHeight }), new PresetGeometry(new AdjustValueList()) { Preset = ShapeTypeValues.Rectangle });
var picture = new DocumentFormat.OpenXml.Drawing.Picture(nvps, nvpicprops, blipFill, shapeProps);
var position = new DocumentFormat.OpenXml.Drawing.Spreadsheet.AbsoluteAnchor(
new DocumentFormat.OpenXml.Drawing.Spreadsheet.Position() { X = col * cellWidth + offsetX, Y = row * cellHeight + offsetY },
new DocumentFormat.OpenXml.Drawing.Spreadsheet.Extent() { Cx = imageWidth, Cy = imageHeight }, picture,
new DocumentFormat.OpenXml.Drawing.Spreadsheet.ClientData());
drawingsPart.WorksheetDrawing = new DocumentFormat.OpenXml.Drawing.Spreadsheet.WorksheetDrawing(position);
}