none
Problem to refer to file RRS feed

  • Question

  • Hi,
    I get

    System.IO.IOException was unhandled
      HResult=-2146232800
      Message=Cannot modify a read-only container.
      Source=WindowsBase
      StackTrace:
           at System.IO.Packaging.Package.ThrowIfReadOnly()
           at System.IO.Packaging.Package.CreatePart(Uri partUri, String contentType, CompressionOption compressionOption)
           at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateMetroPart(Uri partUri, String contentType)
           at DocumentFormat.OpenXml.Packaging.OpenXmlPart.CreateInternal(OpenXmlPackage openXmlPackage, OpenXmlPart parent, String contentType, String targetExt)
           at DocumentFormat.OpenXml.Packaging.OpenXmlPartContainer.InitPart[T](T newPart, String contentType, String id)
           at DocumentFormat.OpenXml.Packaging.OpenXmlPartContainer.InitPart[T](T newPart, String contentType)
           at DocumentFormat.OpenXml.Packaging.OpenXmlPartContainer.AddNewPartInternal[T]()
           at DocumentFormat.OpenXml.Packaging.OpenXmlPartContainer.AddNewPart[T]()
           at WindowsFormsApplication2.Form1.InsertWorksheet(WorkbookPart workbookPart) in c:\dp13\General Application\WindowsFormsApplication9_4_0_2\WindowsFormsApplication2\Form1.cs:line 457
           at WindowsFormsApplication2.Form1.InsertText(SpreadsheetDocument spreadSheet, String SheetName0, String text, String CellRowRef0, UInt32 CellColRef0) in c:\dp13\General Application\WindowsFormsApplication9_4_0_2\WindowsFormsApplication2\Form1.cs:line 626
           at WindowsFormsApplication2.Form1.menuItem5_Click(Object sender, EventArgs e) in c:\dp13\General Application\WindowsFormsApplication9_4_0_2\WindowsFormsApplication2\Form1.cs:line 158
           at System.Windows.Forms.MenuItem.OnClick(EventArgs e)
           at System.Windows.Forms.MenuItem.MenuItemData.Execute()
           at System.Windows.Forms.Command.Invoke()
           at System.Windows.Forms.Command.DispatchID(Int32 id)
           at System.Windows.Forms.Control.WmCommand(Message& m)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
           at System.Windows.Forms.Form.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.Run(Form mainForm)
           at WindowsFormsApplication2.Program.Main() in c:\dp13\General Application\WindowsFormsApplication9_4_0_2\WindowsFormsApplication2\Program.cs:line 19
           at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException: 
    due to this line

                WorksheetPart newWorksheetPart = workbookPart.AddNewPart<WorksheetPart>();


                
    that is from 2nd event below. Why?
            public static void InsertText(SpreadsheetDocument spreadSheet, string SheetName0, string text, string CellRowRef0, uint CellColRef0)
            {
                //using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
                // Open the document for editing.
                //Using(SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
                //{
                // Get the SharedStringTablePart. If it does not exist, create a new one.
                SharedStringTablePart shareStringPart;
                if (spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Count() > 0)
                {
                    shareStringPart = spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
                }
                else
                {
                    shareStringPart = spreadSheet.WorkbookPart.AddNewPart<SharedStringTablePart>();
                }
    
                // Insert the text into the SharedStringTablePart.
                // int index = InsertSharedStringItem(text, shareStringPart);
    
                // Insert a new worksheet.
                WorksheetPart worksheetPart = InsertWorksheet(spreadSheet.WorkbookPart);
    
                // Insert cell A1 into the new worksheet.
                Cell cell = InsertCellInWorksheet(CellRowRef0, CellColRef0, worksheetPart);
    
                // Set the value of cell A1.
                cell.CellValue = new CellValue(text);
                cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
    
                // Save the new worksheet.
                worksheetPart.Worksheet.Save();
                //}
            }
            private static WorksheetPart InsertWorksheet(WorkbookPart workbookPart)
            {
                // Add a new worksheet part to the workbook.
                WorksheetPart newWorksheetPart = workbookPart.AddNewPart<WorksheetPart>();
                newWorksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(new SheetData());
                newWorksheetPart.Worksheet.Save();
    
                DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
                string relationshipId = workbookPart.GetIdOfPart(newWorksheetPart);
    
                // Get a unique ID for the new sheet.
                uint sheetId = 1;
                if (sheets.Elements<Sheet>().Count() > 0)
                {
                    sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
                }
    
                string sheetName = "Sheet" + sheetId;
    
                // Append the new worksheet and associate it with the workbook.
                Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
                sheets.Append(sheet);
                workbookPart.Workbook.Save();
    
                return newWorksheetPart;
            }


    Many Thanks & Best Regards, Hua Min


    Tuesday, November 15, 2016 2:01 AM

Answers

  • Hi,

    According to the exception message: Message=Cannot modify a read-only container.

    I think you open the document as read-only.

     

    Based on your last thread: you are using:

         using (FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {                 
                        using (SpreadsheetDocument doc = SpreadsheetDocument.Open(fs, false))
                        {

    You need to change the false into True because you would modify the document.

    For more information, please visit How to: Open a spreadsheet document for read-only access (Open XML SDK)

    Regards,

    Celeste


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Jackson_1990 Wednesday, November 16, 2016 2:13 AM
    Tuesday, November 15, 2016 9:17 AM
    Moderator