Hello I have this code where i create an xlsx file and i need to pre set the width of the xlsx sheet cells. The actual problem is that when i open the excell i need to double c
Mubashar Ahmad's answer helped me, thank you for that. I wanted to include how I used it in my project. I have made it into an extension method and refactored it.
Here is the implementation, which sets the cell width for the first column in the worksheet.
worksheet.Column(1).SetTrueColumnWidth(28);
Here is the extension method for setting a more accurate column width in EPPlus Excel files, note that this method must be inside of a static class:
public static void SetTrueColumnWidth(this ExcelColumn column, double width)
{
// Deduce what the column width would really get set to.
var z = width >= (1 + 2 / 3)
? Math.Round((Math.Round(7 * (width - 1 / 256), 0) - 5) / 7, 2)
: Math.Round((Math.Round(12 * (width - 1 / 256), 0) - Math.Round(5 * width, 0)) / 12, 2);
// How far off? (will be less than 1)
var errorAmt = width - z;
// Calculate what amount to tack onto the original amount to result in the closest possible setting.
var adj = width >= 1 + 2 / 3
? Math.Round(7 * errorAmt - 7 / 256, 0) / 7
: Math.Round(12 * errorAmt - 12 / 256, 0) / 12 + (2 / 12);
// Set width to a scaled-value that should result in the nearest possible value to the true desired setting.
if (z > 0)
{
column.Width = width + adj;
return;
}
column.Width = 0d;
}