Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto column width in EPPlus

Use AutoFitColumns, but you have to specify the cells, i assume the entire worksheet:

VB.NET

Worksheet.Cells(Worksheet.Dimension.Address).AutoFitColumns()

C#

Worksheet.Cells[Worksheet.Dimension.Address].AutoFitColumns();

Please note you need to call this method after filling the worksheet.


I have used this code with the version 3.1.3.0 of EPPlus and it is working:

worksheet.Column(1).AutoFit();

where a worksheet is the variable referencing the worksheet I have created in my code (not a class with a static method!).

Obviously you have to call this method after you have filled the columns.


Just wanted to point out you can fit cells with out specifying the range, just make sure to call this after you've formatted all columns etc:

worksheet.Cells.AutoFitColumns()

I know this is an old question, but I use the code below and it seems to directly address what you have tried to do.

using (var xls = new ExcelPackage())
{
    var ws = xls.Workbook.Worksheets.Add("Some Name");

    //**Add Column Names to worksheet!**
    //**Add data to worksheet!**

    const double minWidth = 0.00;
    const double maxWidth = 50.00;

    ws.Cells.AutoFitColumns(minWidth, maxWidth);

    return pkg.GetAsByteArray();
}

I know is a little bit late but I've had the same problem today. If you have a worksheet.DefaultColWidthdefined, it won't work. I've removed that line and added Worksheet.cells.AutoFitColumns(); and it works now.