Search code examples
epplus

EPPlus sort the generated table


Once I've generated my table via EPPlus, how do I tell it that I'd like it to automatically sort by columns? I'd like to basically tell it to sort by column A, then, B, then C.

I'm generating the table like so:

internal static void MakeItATable(this ExcelWorksheet ws, string tableName = "Table1")
{
    var addr = new ExcelAddressBase(ws.Dimension.Address);
    var tbl = ws.Tables.Add(addr, tableName);
    tbl.ShowHeader = true;
    ws.Cells[ws.Dimension.Address].AutoFitColumns();
}

Solution

  • Since you know there is a header and you know the dimensions of the table from its Address, you can just tell EPPlus to skip the first row:

    var s = tbl.Address.Start;
    var e = tbl.Address.End;
    
    //Add 1 to skip the header
    ws.Cells[s.Row + 1, s.Column, e.Row, e.Column].Sort(new[] { 0, 1, 2 });