当ExcËl工作表中的数据很大时,可以在选定区域中添加“文本过滤器”,“数字过滤器”,“颜色过滤器”或“日期过滤器”以过滤数据。筛选后的工作表将显示您需要的数据,并隐藏其余的数据。
在下面显示的工作表中,您可以在“类别”列中添加文本过滤器,以使工作表仅显示数据的一种类别。您可以在“数量”列中添加数字过滤器,以使工作表显示包含80-100之间数字的行;您可以添加滤色器以显示具有背景色的行;您还可以在“日期”列中添加日期过滤器,以显示特定月份内的数据。
首先,将Spire。Xls。jar文件导入Java应用程序。
AddSpire。Xls。jar作为依赖
方法1:DownloadFreeSpire。XLSforJavapack,unzipitandyou’ll得到Spire。文件。“lib”文件夹中的jar文件。将jar文件作为依赖项导入项目中。
方法2:如果要创建Maven项目,则可以通过将以下配置添加到pom。xml来轻松添加jar依赖项。
<仓库><资料库><ID>com。e-冰蓝</ID><名称>e-冰蓝</名称><网址>http://repo。e-冰蓝。com/nexus/content/groups/public/</网址></资料库></仓库><依存关系><依赖><groupId>e-冰蓝</groupId><artifactId>spire。xls。自由</artifactId><版>2。2。0</版></依赖></依存关系>
Example 1。 文字过滤器
//创建一个工作簿对象工作簿 b = 新 工作簿();//加载示例Excel文件b。loadFromFile(“ C:\\ Users \\ Administrator \\ Desktop \\ sample。xlsx”);//获取第一个工作表工作表 片 = b。得到Work片s()。得到(0);//获取AutoFiltersCollection对象AutoFiltersCollection 过滤器 = 片。得到AutoFilters();//设置要添加过滤条件的单元格范围过滤器。setRange(片。得到CellRange(2,2,16,5));//将过滤器添加到所选范围的第二列并设置过滤条件,即文本“ C”过滤器。addFilter(1, “C”);//执行过滤功能过滤器。过滤();//保存到文件b。saveToFile(“ TextFilter。xlsx”, Excel版本。2013版);
Example 2。 号码过滤器
//创建一个工作簿对象工作簿 b = 新 工作簿();//加载示例Excel文件b。loadFromFile(“ C:\\ Users \\ Administrator \\ Desktop \\ sample。xlsx”);//获取第一个工作表工作表 片 = b。得到Work片s()。得到(0);//获取AutoFiltersCollection对象AutoFiltersCollection 过滤器 = 片。得到AutoFilters();//设置要添加过滤条件的单元格范围过滤器。setRange(片。getCellRange(2,2,16,5));//Add a custom 过滤 to the third column of the selected range and set the 过滤 criteria, which is to select the number greater than or equal to 80 and less than or equal to 100过滤器。customFilter(2, FilterOperatorType。大于等于, 80, 真正, FilterOperatorType。小于等于, 100);//执行过滤功能过滤器。过滤();//保存到文件b。saveToFile(“ NumberFilter。xlsx”, Excel版本。2013版);
Example 3。 彩色滤光片
//创建一个工作簿对象工作簿 b = 新 工作簿();//加载示例Excel文件b。loadFromFile(“ C:\\ Users \\ Administrator \\ Desktop \\ sample。xlsx”);//获取第一个工作表工作表 片 = b。get工作表s()。get(0);//获取AutoFiltersCollection对象AutoFiltersCollection 过滤器 = 片。getAutoFilters();//设置要添加过滤条件的单元格范围过滤器。setRange(片.getCellRange(2,2,16,5));//Add a color filter to the first column of the selected range and set the filter criteria, that is, the background color of cell B4过滤器.addFillColorFilter(0, 片.getCellRange(“ B4”)。getStyle()。getColor());//执行过滤功能过滤器.filter();//保存到文件b.saveToFile(“ ColorFilter.xlsx”, Excel版本.2013版);
Example 4. 日期筛选
//创建一个工作簿对象工作簿 b = 新 工作簿();//加载示例Excel文件b.loadFromFile(“ C:\\ Users \\ Administrator \\ Desktop \\ sample.xlsx”);//获取第一个工作表工作表 片 = b.getWork片s()。get(0);//获取AutoFiltersCollection对象AutoFiltersCollection 过滤器 = 片.getAutoFilters();//设置要添加过滤条件的单元格范围过滤器.setRange(片.getCellRange(2,2,16,5));//Add a date filter in the fourth column of the selected range, using April 2019年年 as the filter criteria过滤器.addDateFilter(3, DateTimeGroupingType.月, 2019, 4, 1, 0, 0, 0 );
//执行过滤功能
过滤器.filter();
//保存到文件
b.saveToFile(“ DateFilter.xlsx”, Excel版本.2013版);
from: https://dev.to//eiceblue/add-filters-to-excel-in-java-cfb