OpenXML Custom column width not working

∥☆過路亽.° 提交于 2019-12-02 04:14:44

The order of your elements is slightly out. The Columns should be placed before the SheetData rather than after. The relevant part of the XML schema for a Worksheet is:

<xsd:complexType name="CT_Worksheet">
    <xsd:sequence>
    <xsd:element name="sheetPr" type="CT_SheetPr" minOccurs="0" maxOccurs="1"/>
    <xsd:element name="dimension" type="CT_SheetDimension" minOccurs="0" maxOccurs="1"/>
    <xsd:element name="sheetViews" type="CT_SheetViews" minOccurs="0" maxOccurs="1"/>
    <xsd:element name="sheetFormatPr" type="CT_SheetFormatPr" minOccurs="0" maxOccurs="1"/>
    <xsd:element name="cols" type="CT_Cols" minOccurs="0" maxOccurs="unbounded"/>
    <xsd:element name="sheetData" type="CT_SheetData" minOccurs="1" maxOccurs="1"/>

To fix your code you could either remove the SheetData from your new Worksheet line and add the SheetData after the Columns:

worksheetPart.Worksheet = new Worksheet(new SheetViews(new SheetView { WorkbookViewId = 0, ShowGridLines = new BooleanValue(false) }));

//....code omitted for brevity

Columns columns = new Columns();

columns.Append(new Column() { Min = 1, Max = 3, Width = 20, CustomWidth = true });
columns.Append(new Column() { Min = 4, Max = 4, Width = 30, CustomWidth = true });

worksheetPart.Worksheet.Append(columns);
worksheetPart.Worksheet.Append(new SheetData());

OR you could leave the new Worksheet code as-is and use the InsertBefore method when adding the Columns to insert them before the SheetData:

Columns columns = new Columns();

columns.Append(new Column() { Min = 1, Max = 3, Width = 20, CustomWidth = true });
columns.Append(new Column() { Min = 4, Max = 4, Width = 30, CustomWidth = true });

var sheetdata = worksheetPart.Worksheet.GetFirstChild<SheetData>();
worksheetPart.Worksheet.InsertBefore(columns, sheetdata);

One other thing to note - you ought to wrap the SpreadsheetDocument.Create in a using statement. This will clean up any resources and save the file for you at the end of your changes i.e.:

using (var _document = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
{
    //all your OpenXml code here...
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!