Reputation: 1703
My task is parse an excel file and converted it to web table. To achieve that objective, I need the column numbers, width of each column, row numbers, and each cell and cell property within the row.
So far, I can get the rows, the cells, the cell property such as border,font, and so on. But I can't get the column width.
When I open the excel file and get columns by following code
Columns columns = sheet.Descendants<Columns>().FirstOrDefault()
But, sometimes I can get it, sometimes the value is null.
I read the excel file by openxml tools. The following code is not always there.
Columns columns1 = new Columns();
Column column1 = new Column(){ Min = (UInt32Value)7U, Max = (UInt32Value)7U, Width = 39.6328125D, CustomWidth = true };
columns1.Append(column1);
If you open an empty excel file and do not change column width, then you save it. The code is not there.
So my question is how can I get the column width?
Upvotes: 0
Views: 2692
Reputation: 2639
A column width can have either the default width or custom width. As you state, the custom width can be read from Column.Width property. If the default column width is set, it can be read from SheetFormatProperties Class. However, if DefaultColumnWidth
property is set to null, The default column width is 8.43 characters.
To get the DefaultColumnWidth
:
using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(filePath, true))
{
WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
string relationshipId = sheets.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
Worksheet workSheet = worksheetPart.Worksheet;
var sheetFormatProps = workSheet.SheetFormatProperties;
var defaultColWidth = sheetFormatProps.DefaultColumnWidth;
if (defaultColWidth == null)
{
defaultColWidth = 8.43;
}
}
Upvotes: 2