Gargoyle
Gargoyle

Reputation: 10324

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();
}

Upvotes: 1

Views: 1202

Answers (2)

Ernie S
Ernie S

Reputation: 14250

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 });

Upvotes: 0

Wolfgang Jacques
Wolfgang Jacques

Reputation: 769

You may sort the table with

ws.Cells[tbl.Address.Address].Sort(new[] { 0, 1, 2});

with {0, 1, 2} meaning the first, second and third column of the table (not necessarily the worksheet)

Unluckily, there seems to be no option to tell if Headers are present or not, so the headers dive down into the table.

If you manage to sort the table without its first line you should succeed, but my brain cannot process this at the moment.

Upvotes: 1

Related Questions