The selected answer above did not fix my problem, but I finally figured it out. The problem was that I was calling a row: Columns columns1=worksheet1.GetFirstChild<Columns>(); there were currently no Columns on the worksheet, so the returned object was empty, and I got a runtime error when I tried to add a column to the Columns object.
The problem is that Excel is very picky. The column element in the actual sheet.xml should be before the sheetdata element. An attempt to add my custom columns to the worksheet resulted in a damaged file due to its placement of the column element after the sheetdata element. Since I knew that this should be before the sheetdata element, I had to insert it at the beginning of the worksheet and not add it to the worksheet. Here is the code that worked for me:
// Save the stylesheet formats stylesPart.Stylesheet.Save(); // Create custom widths for columns Columns lstColumns = worksheetPart.Worksheet.GetFirstChild<Columns>(); Boolean needToInsertColumns = false; if (lstColumns == null) { lstColumns = new Columns(); needToInsertColumns = true; } // Min = 1, Max = 1 ==> Apply this to column 1 (A) // Min = 2, Max = 2 ==> Apply this to column 2 (B) // Width = 25 ==> Set the width to 25 // CustomWidth = true ==> Tell Excel to use the custom width lstColumns.Append(new Column() { Min = 1, Max = 1, Width = 25, CustomWidth = true }); lstColumns.Append(new Column() { Min = 2, Max = 2, Width = 9, CustomWidth = true }); lstColumns.Append(new Column() { Min = 3, Max = 3, Width = 9, CustomWidth = true }); lstColumns.Append(new Column() { Min = 4, Max = 4, Width = 9, CustomWidth = true }); lstColumns.Append(new Column() { Min = 5, Max = 5, Width = 13, CustomWidth = true }); lstColumns.Append(new Column() { Min = 6, Max = 6, Width = 17, CustomWidth = true }); lstColumns.Append(new Column() { Min = 7, Max = 7, Width = 12, CustomWidth = true }); // Only insert the columns if we had to create a new columns element if (needToInsertColumns) worksheetPart.Worksheet.InsertAt(lstColumns, 0); // Get the sheetData cells SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
Hope this helps someone!
source share