Search code examples
excelopenxml-sdk

File created in Open XML SDK 2.5 crashes excel when selecting print


I created an excel document in c# using the open xml 2.5 sdk. The file opens in excel and works fine till I select print. At this point, excel crashes with the error "Excel has stopped working". I am using Excel 2016. If I save the file first, before selecting print, the problem is fixed.

I was able to find the solution, but couldn't find this question on stackoverflow, so I'm posting and answering my own question. If anyone has any comments for improvement or a better solution, please let me know.

Thanks.


Solution

  • This link pointed me in the correct direction. The issue was that I had not added bookviews to my file. The solution in code is:

    WorkbookPart workbookPart = document.AddWorkbookPart();
    workbookPart.Workbook = new Workbook();
    WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
    worksheetPart.Worksheet = new Worksheet();
    
    BookViews bookViews = new BookViews();
    WorkbookView workbookView = new WorkbookView();
    bookViews.Append(workbookView);
    workbookPart.Workbook.Append(bookViews);
    

    In the original link, one of the comments mentions adding BookViews prior to Sheets. I found this to be true.