当Excel中的数据较多时,我们可以在某列或所有列添加筛选器,对数据进行筛选来获取有用的信息。本文将介绍如何使用Spire.XLS在Excel中添加筛选器、设置筛选项目并执行筛选。
C#
//创建Workbook对象
Workbook workbook = new Workbook();
//加载现有的Excel文档
workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.xlsx");
//获取第一个工作表
Worksheet sheet = workbook.Worksheets[0];
//获取筛选器对象
AutoFiltersCollection filters = sheet.AutoFilters;
//设置筛选器的添加位置:第二列
filters.Range = sheet.Range[1, 2, sheet.LastRow, 2];
//添加筛选项目
filters.AddFilter(0, "测试");
//执行筛选
filters.Filter();
//保存文档
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2010);
VB.NET
'创建Workbook对象
Dim workbook As New Workbook()
'加载现有的Excel文档
workbook.LoadFromFile("C:\Users\Administrator\Desktop\sample.xlsx")
'获取第一个工作表
Dim sheet As Worksheet = workbook.Worksheets(0)
'获取筛选器对象
Dim filters As AutoFiltersCollection = sheet.AutoFilters
'设置筛选器的添加位置:第二列
filters.Range = sheet.Range(1, 2, sheet.LastRow, 2)
'添加筛选项目
filters.AddFilter(0, "测试")
'执行筛选
filters.Filter()
'保存文档
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2010)