本主题为您提供了有关如何使用 C# 过滤 Excel 表中的数据的必要详细信息。示例代码显示了如何在 XLSX 文件中使用 C# 在 Excel 中添加过滤器。此外,您可以通过几个简单的步骤使用 C# 在 Excel 电子表格中创建动态过滤器。
使用 C# 在 Excel 表中过滤数据的步骤
- 从 NuGet.org 获取 Aspose.Cells for .NET 包
- 将 Aspose.Cells 命名空间导入项目
- 使用 SetLicense 方法实例化和设置 License 对象
- 从头开始创建 Workbook
- 将数据插入工作簿中的第一个工作表
- 设置 AutoFilter 范围并添加自定义过滤
- 将过滤后的数据保存到 XLSX 文件
动态过滤数据意味着仅显示那些涵盖某些条件的记录。如果您只想获取特定水果(在本例中为葡萄)的记录,此示例演示 Excel 的自动筛选功能,并帮助您了解如何在 C# 中的 Excel 中应用自定义筛选。
使用 C# 过滤 Excel 表中数据的示例代码
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"); | |
} | |
} | |
} |
代码段(上图)实例化了一个空白工作簿,然后将数据插入到第一个工作表中的一系列单元格中。 C#代码设置Excel自动过滤范围;它确实在 Excel 电子表格中添加或应用自定义过滤器。最后,它将过滤后的数据保存到磁盘上的 XLSX 文件中。您可能还对 如何在 C# 中创建 Excel 饼图 主题感兴趣。