I have this code
ImagePartType ipt = ImagePartType.Jpeg;
DrawingsPart drawingsPart1;
ImagePart imagePart1;
WorksheetDrawing worksheetDrawing1;
if (sheet1.DrawingsPart == null)
{
drawingsPart1 = sheet1.AddNewPart<DrawingsPart>();
imagePart1 = drawingsPart1.AddImagePart(ipt, sheet1.GetIdOfPart(drawingsPart1));
worksheetDrawing1 = new WorksheetDrawing();
}
but at
drawingsPart1 = sheet1.AddNewPart<DrawingsPart>();
it throws an Exception " Only one instance of the type is allowed for this parent"
and
sheet1.DrawingsPart is null, so there is no other Drawing part. Any idea how to solve this? This exact code is working in my second project, with same excel file! Thank you.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(outputDocumentStream, true))
{
wbPart = document.WorkbookPart;
document.Close();
}
sheet1 = GetWorksheetPart(wbPart, "Sheet1")
and
public WorksheetPart GetWorksheetPart(WorkbookPart workbookPart, string sheetName)
{
string relId = workbookPart.Workbook.Descendants<Sheet>().First(s => sheetName.Equals(s.Name)).Id;
return (WorksheetPart)workbookPart.GetPartById(relId);
}
I can't write more codes, because it is not open source project. Basically I get worksheet and worksheet part by typing sheet name, and after that i have to insert picture in some cell.
WorkbookPart wbPart;
This fixed it. InsertImage method was outside of the brackets. I don't know why, but this fixed my code.