1

I'm attempting to alter a pre-existing office document by inserting an externally loaded image using open XML SDK 2.5. I plan to do this in excel by appending a worksheet that to the workbook and then doing all of the work there. However, I can't seem to get around one error in particular.

My code is:

    public void insert(String filepath)
    {
        SpreadsheetDocument doc = SpreadsheetDocument.Open(filepath, false);

        // Add a WorksheetPart to the WorkbookPart.
        WorksheetPart worksheetPart = doc.WorkbookPart.AddNewPart<WorksheetPart>();
        worksheetPart.Worksheet = new Worksheet(new SheetData());

        // Add Sheets to the Workbook.
        Sheets sheets = doc.WorkbookPart.Workbook.
            AppendChild<Sheets>(new Sheets());

        // Append a new worksheet and associate it with the workbook.
        Sheet sheet = new Sheet()
        {
            Id = doc.WorkbookPart.
            GetIdOfPart(worksheetPart),
            SheetId = 1,
            Name = "mySheet"
        };
        sheets.Append(sheet);

        // Close the document.
        doc.Close();
    }

Line 6 (adding a new worksheet part) throws an IO exception each time I try to test the program. Most of this code was taken from the MSDN. The very same site suggested that if I'm getting an IO exception, I may have input the wrong filepath, but that is definitely not the case. I also verified that the members I'm accessing are indeed public, so I'm a bit confused. Can anyone tell me what this error may be? I'm hoping it's something simple. This is my first time using C#.

EDIT: I should mention the exception message also states "cannot open a read only container", but I have verified that the file is NOT read only and excel is NOT open.

1
  • @Donal No I do not. And I don't see excel in the list of running processes. Commented Jul 1, 2015 at 22:19

1 Answer 1

2

You are passing false to the isEditable argument when opening the file.

SpreadsheetDocument.Open(filepath, false)

This makes the document read-only. If you change it to true, it should work better.

More information:


I would first read the file content into a MemoryStream, and open that instead. This would reduce the risk of file corruption.

var memory = new MemoryStream();
using (var file = File.OpenRead(filepath))
{
    file.CopyTo(memory);
}
memory.Position = 0;

var doc = SpreadsheetDocument.Open(memory, true);

//...

doc.Close();

File.WriteAllBytes(filepath, memory.ToArray());
Sign up to request clarification or add additional context in comments.

1 Comment

Oh wow thank you! A circumstance of my inexperience with the tool. Now I just have file corruption to worry about!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.