Home » excel » c# – Setting Excel spreadsheet column properties issue

c# – Setting Excel spreadsheet column properties issue

Posted by: admin March 9, 2020 Leave a comment

Questions:

I’m trying to set up default column width in Excel spreadsheet using OpenXML framework and as a result I’ve got broken file. Here is code

private void initSpreadsheetDocument()
{
    // Add a WorkbookPart to the spreadsheet document.
    WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
    workbookpart.Workbook = new Workbook();

    var sheetData = new SheetData();
    var properties = new SheetFormatProperties { DefaultColumnWidth = 25D };

    Worksheet worksheet = new Worksheet();
    worksheet.AppendChild(sheetData);

    // here is line of code that corrupt file
    // without it - file is being generated properly
    worksheet.AppendChild(properties);  ![enter image description here][1]

    // Add a WorksheetPart to the WorkbookPart.
    WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
    worksheetPart.Worksheet = worksheet;

    // Init sheets
    sheetsStorage = new Sheets();

    defaultSheet = new Sheet();
    defaultSheet.Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart);
    defaultSheet.SheetId = 1;
    defaultSheet.Name = DEFAULT_SHEET_NAME;

    sheetsStorage.AppendChild(defaultSheet);

    spreadsheetDocument.WorkbookPart.Workbook.AppendChild(sheetsStorage);
    spreadsheetDocument.WorkbookPart.Workbook.Save();
}

here is error screenshot

I was trying to use “Append” vs “AppendChild” but result was the same

Does anybody has a point of view how to sort it out?

How to&Answers:

Okay. The reason is SheetFormatProperties Object has required attribute defaultRowHeight. You could even assign defaultRowHeight = 0, but it must presents. So use

SheetFormatProperties sheetFormatProperties1 = new SheetFormatProperties(){ DefaultColumnWidth = 12.75D, DefaultRowHeight = 0D};

and be happy=) Слава Украине!