I'm developing a class, which allows users to create Excel spreadsheets on the fly (using OpenXML api) and I need to calculate columns width, so that they auto-fit the widest cell in the column.
I have the following code to calculate each column's width (using the formula from here and this tutorial):
private double CalculateColumnWidth(int textLength)
{
var font = new System.Drawing.Font("Calibri", 11);
float digitMaximumWidth = 0;
using(var graphics = Graphics.FromImage(new Bitmap(200, 200)))
{
for(var i = 0; i < 10; ++i)
{
var digitWidth = graphics.MeasureString(i.ToString(), font).Width;
if (digitWidth > digitMaximumWidth)
digitMaximumWidth = digitWidth;
}
}
return Math.Truncate((textLength * digitMaximumWidth + 5.0) / digitMaximumWidth * 256.0) / 256.0;
}
This works fine, the only question is: Is there any way to get rid of the Bitmap and Graphics objects, that I don't really need to calculate the Excel's column width? Why is the Graphics object necessary to do this? Thx in advance