简体   繁体   中英

OpenXML Excel file corrupted when trying to hide a column

I have been struggling to understand as to why my excel file gets corrupted. I am trying to hide certain columns (in this case Column A). Using OpenXML Productivity Tool, I have viewed the code build-up and this is the output:

Worksheet worksheet1 = new Worksheet();
Columns columns1 = new Columns();
Column column1 = new Column(){ Min = (UInt32Value)1U, Max = (UInt32Value)1U, Width = 0D, Hidden = true, CustomWidth = true };
columns1.Append(column1);
SheetFormatProperties sheetFormatProperties1 = new SheetFormatProperties(){ DefaultRowHeight = 15D, DyDescent = 0.25D };
SheetData sheetData1 = new SheetData();
Row row1 = new Row(){ RowIndex = (UInt32Value)1U };
Cell cell1 = new Cell(){ CellReference = "A1", DataType = CellValues.String };
CellValue cellValue1 = new CellValue();
cellValue1.Text = "Table Id";
cell1.Append(cellValue1);
Cell cell2 = new Cell(){ CellReference = "B1", DataType = CellValues.String };
CellValue cellValue2 = new CellValue();
cellValue2.Text = "Table";
cell2.Append(cellValue2);
row1.Append(cell1);
row1.Append(cell2);
Row row2 = new Row(){ RowIndex = (UInt32Value)2U };
Cell cell6 = new Cell(){ CellReference = "A2", DataType = CellValues.String };
CellValue cellValue6 = new CellValue();
cellValue6.Text = "1";
cell6.Append(cellValue6);
Cell cell7 = new Cell(){ CellReference = "B2", DataType = CellValues.String };
CellValue cellValue7 = new CellValue();
cellValue7.Text = "Options";
cell7.Append(cellValue7);
row2.Append(cell6);
row2.Append(cell7);
sheetData1.Append(row1);
sheetData1.Append(row2);
worksheet1.Append(columns1);
worksheet1.Append(sheetFormatProperties1);
worksheet1.Append(sheetData1);
part.Worksheet

As seen this is basically an example with two rows. Column A should be hidden, but when opening the XML file it seems to be corrupted. Any ideas as to what I am perhaps missing here? An alternative approach I have tried to use microsoft documentation to get all cells for a specific column - https://docs.microsoft.com/en-us/office/open-xml/how-to-get-a-column-heading-in-a-spreadsheet I was unable to find any way to hide all of the selected cells (tried using OpenXMLAttribute with the value hidden, but had no success.)

I was able to resolve this issue thanks to this post:
Creating custom column widths in OpenXML (excel)

It seems that I need to insert the columns I am specifically hiding in a new excel file on the first index.

Why don't you try EPPlus ?

With EPPLus, you can do something like this:

worksheet.Cells.AutoFitColumns();
worksheet.Column(1).Hidden = true;

Original post is here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM