epplus

EPPlus AutoFitColumns not working


Seems to be a few folks with this problem, and usually it's solved because they haven't loaded data yet. I've loaded my data, but the Autofit is still not working.

Dim fi As New FileInfo(fileDialog.FileName)
Dim pck As New ExcelPackage(fi)

Dim epWs As ExcelWorksheet = pck.Workbook.Worksheets.Add("My Sheet")
epWs.Cells("A1").LoadFromDataTable(data, True)

With epWs.Cells("A1:G1")
    .AutoFilter = True
    .AutoFitColumns()
    .Style.Fill.PatternType = ExcelFillStyle.Solid
    .Style.Fill.BackgroundColor.SetColor(Color.DodgerBlue)
    .Style.Font.Color.SetColor(Color.White)
End With

pck.Save()

This results in a file where the columns are all their default widths. There are no formulas in any of the cells, and none are merged.

I then kicked it up and tried using BestFit, but this is also not working.

        For i = 1 To 7
            epWs.Column(i).BestFit = True
        Next

(weird how the Columns collection is not zero-based)

Anyway, does anyone have any pointers? Thanks


Solution

  • You need to call AutoFitColumns on the entire range, not just A1:G1. Do something like:

    epWs.Cells.AutoFitColumns();
    

    See this for more info:

    EPPLUS AutoFit cells