insert an image in Excel file with C# openXml


Im made a function in C# to work with azure function but at first i got this message:

System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

Looking on the internet it said it was because Azure Function doesn't work with the Excel Interop dll and a way to achieve this was using the OpenXml SDK, so went and made a OpenXml method:

public static void AddImage(string filepath, string imagepath)
     using (SpreadsheetDocument spreadsheet = SpreadsheetDocument.Open(filepath, true))
         WorkbookPart wb = spreadsheet.WorkbookPart;
         string sheetName = "sheet2";
         string relId = wb.Workbook.Descendants<Sheet>().First(s => sheetName.Equals(s.Name)).Id;
         WorksheetPart wp = (WorksheetPart) wb.GetPartById(relId);
         DrawingsPart drawingsPart1 = wp.AddNewPart<DrawingsPart>();
         ImagePart imagePart = drawingsPart1.AddImagePart(ImagePartType.Gif);

         using (FileStream stream = new FileStream(imagepath, FileMode.Open))
         GenerateDrawingsPart1Content(drawingsPart1, drawingsPart1.GetIdOfPart(imagePart));

    Worksheet worksheet = wp.Worksheet;
    Drawing drawing1 = new Drawing() { Id = wp.GetIdOfPart(drawingsPart1) };

it goes well till he gets to:

DrawingsPart drawingsPart1 = wp.AddNewPart<DrawingsPart>();

And now I keep getting this error:  

"Only one instance of the type is allowed for this parent."

any suggestions to fix the error? is there another way to make the "insert image on excel" in a function other than using OpenXml or Excel Interop in Azure Functions?

asked on Stack Overflow May 13, 2021 by Luigi

0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0