So Basically I am trying to fix the width of the Column to do so I am using the following Code,
private double GetWidth(string text)
{
//width = Truncate([{Number of Characters} * {Maximum Digit Width} + {5 pixel padding}]/{Maximum Digit Width}*256)/256
var width = Math.Truncate((text.Length * _maxDigitWidth + 5) / _maxDigitWidth * 256) / 256;
return width < _minCellWidth ? _minCellWidth : width;
}
The working of the code is like firstly it finds the largest text content in a particular column and on the basis of the length of that text it calculates the width of the column. The above code works fine for a certain font size like when the font size is 11. And the _maxDigitWidth = 7.
So the problem is that when I increased the font size to 16 or above then the above code don't calculate the correct width.
This is the result what I am getting
And this is the result what I need
Also in my code I have the facility to also pass the fontSize like this
private double GetWidth(string text, double longestCellWidth)
{
//width = Truncate([{Number of Characters} * {Maximum Digit Width} + {5 pixel padding}]/{Maximum Digit Width}*256)/256
var width = Math.Truncate((text.Length * _maxDigitWidth + 5) / _maxDigitWidth * 256) / 256;
return width < _minCellWidth ? _minCellWidth : width;
}
Please help me to solve the problem.
Your code works fine till font size 11 with calibri. For dynamic sizing of cell width for font size greater than 11 with font family Calibri, you can use this code.
private double GetWidth(string text, double longestCellWidth)
{
if (longestCellWidth <= 11)
{
var width = Math.Truncate(Convert.ToDouble((text.Length * 7 + 5)) / 7 * 256) / 256;
return width;
}
else
{
var width = Math.Truncate(Convert.ToDouble((text.Length * 7 + 5)) / 7 * 256) / 256;
var lengthAdjustment = width + text.Length - 4;
var sizeAdjustment = lengthAdjustment + longestCellWidth / 3;
return sizeAdjustment;
}
}
Now the explanation of the code. I observed that
when we increase the text length by 1, our width is supposed to increase by 1.
And, for every 3 points increase in our font size, our width is supposed to be increased by 1.
I implemented the observation in the code and tested it with different examples. It is certainly not "the most effective solution" but does the job pretty well! Feel free to change it according to your needs.