如何使用C#隐藏OpenXML电子表格中的列?

时间:2011-10-20 18:01:33

标签: c# excel openxml

我正在使用带有C#的DocumentFormat.OpenXML。如何隐藏特定列?
代码的某些部分:

using (SpreadsheetDocument sDocument = SpreadsheetDocument.Open(resultFileName, true))
{
    WorkbookPart workbookPart = sDocument.WorkbookPart;
    WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();

    var relId = workbookPart.GetIdOfPart(worksheetPart);

    GenerateWorksheetPartContent(worksheetPart, data, templateSheet);

    var columns = worksheetPart.Worksheet.Descendants<Column>(); <-- Empty

    int[] colomnsToHide = new int[] { 3, 8, 16, 17, 18 };

    foreach (int i in colomnsToHide)
    {
        columns[i].Hidden = true;
    }
}

templateSheet - 来自xlsx-template的SheetData 数据 - 要插入的数据。

有什么建议吗?

1 个答案:

答案 0 :(得分:4)

当存在一些自定义列行为(例如大小,隐藏或分组)时,列后代仅添加到工作表部分。您可以显式添加列定义,如下所示:

Columns columns = new Columns();

// Min & Max refer to the 1-indexed column ordinal
Column column3 = new Column(){ Min = 3, Max = 3, Width = 0, CustomWidth = true, Hidden = true };
Column column8 = new Column(){ Min = 8, Max = 8, Width = 0, CustomWidth = true, Hidden = true };
// ... repeat for each column

columns.Append(column3);
columns.Append(column8);
worksheetPart.Append(columns);

为您要隐藏的每个列执行此操作