【EPplus】Column width discrepancy
description
Hi Jan,
I have noticed that when I set a column width there is a
discrepancy between the width that I set in code and what
Excel reports.
From the code below, Excel reports the width to be 11.27.
Excel reports the height to be exactly what I set.
oSheet.Column(1).Width = 12.0d;
oSheet.Row(1).Height = 27.75d;
Duardo
I have noticed that when I set a column width there is a
discrepancy between the width that I set in code and what
Excel reports.
From the code below, Excel reports the width to be 11.27.
Excel reports the height to be exactly what I set.
oSheet.Column(1).Width = 12.0d;
oSheet.Row(1).Height = 27.75d;
Duardo
comments
TomDierickx wrote Apr 9, 2012 at 8:32 PM
So, for X >= 1.667, you will probably see a true column width of [ROUND(7 * (X - 1/256)) - 5] / 7 rounding this to two decimal places. For example, let's say you try setting the column width to 10 (i.e. X=10), then you will likely really see a value of "ROUND(7 * (10 - 1/256))" = 70 - 5 = 65 / 7 = 9.29
One workaround that seems to work for a variety of sample widths is to create a custom function to "adjust up" the value you think you're setting by an amount that will result in a net value to get you as close as possible (to the nearest 1/7th if > 1.6667 or to the nearest 1/2th if < 1.6667):
oSheet.Column(1).Width = 10 'really ends up being 9.29
oSheet.Column(2).Width = SetTrueColumnWidth(10) ' really ends up being 10.00
where the following function takes your desired column width and modifies it by enough such that the net result of setting the column width will actually end up being what you want it to be:
Private Function SetTrueColumnWidth(ByVal dblWidth As Double) As Double
'DEDUCE WHAT THE COLUMN WIDTH WOULD REALLY GET SET TO
Dim z As Double = 1
If (dblWidth >= (1 + 2 / 3)) Then
Else
End If
'HOW FAR OFF? (WILL BE LESS THAN 1)
Dim errorAmt As Double = 0
errorAmt = dblWidth - z
'CALCULATE WHAT AMOUNT TO TACK ONTO THE ORIGINAL AMOUNT TO RESULT IN THE CLOSEST POSSIBLE SETTING
Dim adjAmt As Double = 0
If (dblWidth >= (1 + 2 / 3)) Then
Else
End If
'RETURN A SCALED-VALUE THAT SHOULD RESULT IN THE NEAREST POSSIBLE VALUE TO THE TRUE DESIRED SETTING
If (z > 0) Then
Else
End If
End Function
grimmdp wrote Apr 2, 2013 at 1:42 PM
Thanks a bunch for posting this, it helped me a ton. Here it is in C# for anyone who need it:
Dean
redaxe wrote Jul 28, 2013 at 8:38 AM
only one issue 3.5 is being calculated as 3.57 but its fine for me. :)
Christophe_ wrote Jan 7, 2015 at 9:07 AM