Reputation: 61
I'm using DocumentFormat.OpenXML with C#. How do I hide specific columns?
Some part of the code:
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 - SheetData from xlsx-template.
data - data to insert.
Any suggestions?
Upvotes: 5
Views: 10271
Reputation: 3636
The Column descendant is only added to the worksheetpart when there is some custom column behavior, such as sizes, hiding, or grouping. You can explicitly add column definitions like this:
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);
Do this for each column you wish to hide
Upvotes: 6