Search code examples
c#excelepplusworksheet

How to Set TwoCellAnchor for Images in EPPlus to Enable "Move and Size with Cells"?


I am using EPPlus to programmatically add images to an Excel worksheet in a .NET application. I need the images to "Move and Size with Cells", which requires setting the EditAs property of the ExcelPicture object to eEditAs.TwoCell. However, when I attempt to set this property, I encounter a System.InvalidOperationException with the message: "EditAs can only be set when CellAnchor is set to TwoCellAnchor".

Here's the relevant portion of my code:

using (MemoryStream imageStream = new MemoryStream(imageData)) { 
var excelPicture = workSheet.Drawings.AddPicture($"Image_{recordIndex}", imageStream);
excelPicture.SetPosition(recordIndex - 1, 2, 0, 2);
excelPicture.SetSize(200, 200);
excelPicture.EditAs = eEditAs.TwoCell; // This line throws the exception
workSheet.Row(recordIndex).Height = 153;}

I understand that the EditAs property can only be set when the picture's anchor is explicitly set to TwoCellAnchor, but I'm not sure how to do this with the EPPlus API. The documentation and examples I've found do not clearly demonstrate how to set the anchor type for an image when adding it to the worksheet.

Questions:

How can I explicitly set an image's anchor to TwoCellAnchor using EPPlus when adding it to a worksheet? Is there an alternative approach to ensuring that images added to an Excel worksheet with EPPlus will "Move and Size with Cells"? Any guidance, code snippets, or references to relevant EPPlus documentation would be greatly appreciated.


Solution

  • excelPicture.ChangeCellAnchor(eEditAs.TwoCell);