OpenXML: Auto Size column width in Excel
c#, openxml, openxml-sdk
Solution
The BestFit property is an information property (possibly for optimisation by Excel). You still need to provide the Width for the Column. This means you have to actually calculate the column width depending on the cell contents. Open XML SDK doesn't do this automatically for you, so it's better that you use a third-party library for this.
Problem
I have written a code to generate Excel file using OpenXML. Below is the code which generates the Columns in the Excel. ``` Worksheet worksheet = new Worksheet(); Columns columns = new Columns(); int numCols = dt1.Columns.Count; for (int col = 0; col < numCols; col++) { Column c = CreateColumnData((UInt32)col + 1, (UInt32)numCols + 1, 20.42578125D); columns.Append(c); } worksheet.Append(columns); ``` Also, I tried below line to create columns. ``` Column c = new Column { Min = (UInt32Value)1U, Max = (UInt32Value)1U, Width = 25.42578125D, BestFit = true, CustomWidth = true }; ``` I thought using `BestFit` it should work. But it doesn't set the auto size.