设置Excel电子表格列属性问题

时间:2012-10-29 10:49:07

标签: c# excel openxml

我正在尝试使用OpenXML框架在Excel电子表格中设置默认列宽,因此我的文件已损坏。这是代码

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是错误截图

我试图使用“Append”vs“AppendChild”,但结果是相同的

有没有人有一个观点如何解决它?

1 个答案:

答案 0 :(得分:20)

好。原因是SheetFormatProperties对象具有必需属性defaultRowHeight。您甚至可以指定defaultRowHeight = 0,但它必须呈现。所以使用

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

并且开心=)СлаваУкраине!