Only one instance of the type is allowed for this

2019-09-19 05:26发布

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.

标签: c# excel openxml
1条回答
干净又极端
2楼-- · 2019-09-19 06:08

WorkbookPart wbPart;

            using (SpreadsheetDocument document = SpreadsheetDocument.Open(outputDocumentStream, true))
            {
                wbPart = document.WorkbookPart;

                InsertImage(GetWorksheetPart(wbPart, sheetNameTopLeft), (int)topLeftRow - 1, (int)topLeftColumn - 1,
                    (int)bottomRightRow - 1, (int)bottomRightColumn - 1, imageStream); //, 250, 200);

                document.Close();
            }

This fixed it. InsertImage method was outside of the brackets. I don't know why, but this fixed my code.

查看更多
登录 后发表回答