Create advanced filter

冷暖自知 提交于 2019-11-29 17:14:16

Since Advanced Filter is an excel function you need the full Excel DOM to access it. Epplus doesnt have that - it just generated the XML to feed to excel which will then apply its "interpretation", so to speak.

But since you have the power of .NET at your disposal, you can use linq fairly easily to do the same thing by querying the cell store and using .distinct() to get the unique list. The only wrinkle is you have to create your own IEquitableComparer. This will do it:

[TestMethod]
public void Distinct_Filter_Test()
{
    //Throw in some data
    var datatable = new DataTable("tblData");
    datatable.Columns.AddRange(new[]
    {
        new DataColumn("Col1", typeof (int)), new DataColumn("Col2", typeof (string))
    });

    var rnd = new Random();
    for (var i = 0; i < 10; i++)
    {
        var row = datatable.NewRow();
        row[0] = rnd.Next(1, 3) ;row[1] = i%2 == 0 ? "even": "odd";
        datatable.Rows.Add(row);
    }

    //Create a test file
    var fi = new FileInfo(@"c:\temp\Distinct_Filter.xlsx");
    if (fi.Exists)
        fi.Delete();

    using (var pck = new ExcelPackage(fi))
    {
        //Load the random data
        var workbook = pck.Workbook;
        var worksheet = workbook.Worksheets.Add("data");
        worksheet.Cells.LoadFromDataTable(datatable, true);

        //Cells only contains references to cells with actual data
        var rows = worksheet.Cells
            .GroupBy(cell => cell.Start.Row)
            .Skip(1) //Exclude header
            .Select(cg => cg.Select(c => c.Value).ToArray())
            .Distinct(new ArrayComparer())
            .ToArray();

        //Copy the data to the new sheet
        var worksheet2 = workbook.Worksheets.Add("Distinct");
        worksheet2.Cells.LoadFromArrays(rows);

        pck.Save();
    }

}


public class ArrayComparer: IEqualityComparer<object[]>
{
    public bool Equals(object[] x, object[] y)
    {
        return !x.Where((o, i) => !o.Equals(y[i])).Any();
    }

    public int GetHashCode(object[] obj)
    {
        //Based on Jon Skeet Stack Overflow Post
        unchecked
        {
            return obj.Aggregate((int) 2166136261, (acc, next) => acc*16777619 ^ next.GetHashCode());
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!