Skip to content

Instantly share code, notes, and snippets.

@aspose-com-kb
Last active October 8, 2021 18:29
How to Filter Data in Excel Table using C#. For complete details on topic refer to: https://kb.aspose.com/cells/net/how-to-filter-data-in-excel-table-using-c-sharp/
using System;
using Aspose.Cells;
namespace FilterDataInExcelTable
{
class Program
{
static void Main(string[] args)
{
//Create License object and set it at the start before using any other APIs
Aspose.Cells.License Aspose_Cells_lic = new Aspose.Cells.License();
Aspose_Cells_lic.SetLicense("Aspose.Cells.lic");
//Create an empty Excel workbook
Workbook FilteringDataWorkbook = new Workbook();
//Get the worksheet at first indexed position in the workbook - default worksheet
Worksheet FilteringDataSheet = FilteringDataWorkbook.Worksheets[0];
//Obtain the cells collection from the first sheet
Cells FilteringDataCells = FilteringDataSheet.Cells;
//Put data/values into the cells for the table
FilteringDataCells["A1"].PutValue("Fruits");
FilteringDataCells["B1"].PutValue("Total");
FilteringDataCells["A2"].PutValue("Blueberries");
FilteringDataCells["B2"].PutValue(2500);
FilteringDataCells["A3"].PutValue("Apples");
FilteringDataCells["B3"].PutValue(1100);
FilteringDataCells["A4"].PutValue("Mangoes");
FilteringDataCells["B4"].PutValue(1500);
FilteringDataCells["A5"].PutValue("Grapes");
FilteringDataCells["B5"].PutValue(1200);
FilteringDataCells["A6"].PutValue("Oranges");
FilteringDataCells["B6"].PutValue(3000);
FilteringDataCells["D1"].PutValue("Count:");
//Specify formula to E1 cell - this formula would give you count
FilteringDataCells["E1"].Formula = "=SUBTOTAL(2,B1:B6)";
//Set the range to which the specified autofilters would be applied
FilteringDataSheet.AutoFilter.Range = "A1:B6";
//Now add your desired filter to first column to select your desired data
FilteringDataSheet.AutoFilter.AddFilter(0, "Grapes");
FilteringDataSheet.AutoFilter.Refresh();
//Save Excel XLSX file
FilteringDataWorkbook.Save("FilteredData.xlsx");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment