0

I write applications that create PDF files and Excel files. While generating PDF files, I noticed that some of the features that were inserted in the file, did not show up visually. I was informed of a statement that "refreshes" the file and now all the features are visible.

I am having the exact same problem with Excel generation. I need one of my columns to self-adjust to the width of the widest entry (in the same fashion as double-click interactively). I was told about this solution:

"In OpenXML you can set the spreadsheet column properties so that it will be auto-sized when the spreadsheet is opened in Excel. Set BestFit=true and CustomWidth=true when creating the column."

How to implement the feature that adjusts an Excel column to the precise width, programmatically??

I added this statement to my source code:

 Column column2 = new Column() { Min = (UInt32Value)2U, Max = (UInt32Value)2U, Width=7, BestFit = true, CustomWidth = true };

But the column is too narrow. I tried without the Width=7 but in that case the width is assumed to be zero an the column disappears altogether.

TIA

Travis Banger
  • 697
  • 1
  • 7
  • 19
  • if you know font family and size of a string you can use GDI+ method "MeasureString()" to get width and height. Then you can apply it to column width or row height. – Francesco Milani May 30 '17 at 14:05

1 Answers1

0

Short answer is no. Setting the BestFit and CustomWidth properties aren't enough. You still have to manually calculate the column width.

It's best to use a third-party library for this. Suggestions are EPPlus, ClosedXML and SpreadsheetLight. All of these free open source libraries provide the auto-fit feature. Disclosure: I wrote SpreadsheetLight.

Vincent Tan
  • 3,058
  • 22
  • 21