In this brief tutorial, you will learn how to apply filter in Excel using Java with the help of a simple step-by-step approach. You can set auto-filter in the worksheet on all the data columns in a desired range of cells and then apply filter against a particular data in any column. At the end the output file is saved as an XLSX file however, you can save it in any other Excel file format as well.
Steps to Apply Filter in Excel using Java
- Add Aspose.Cells library reference using the Maven repository
- Add the reference to Workbook, Worksheet, and Cells classes by using the Import command in the program
- Instantiate an empty workbook object
- Get a reference to the first sheet where sample data is to be added
- Using the cells collection in sheet, fill sample data into the worksheet
- Apply data filter in Excel on the desired range of cells
- Set a particular filter on the first column against particular data
- Save the resultant file as XLSX
Here an empty workbook is created that is filled with some sample data. The reference to cells collection in the worksheet is obtained and the range is set for the filter on this Excel sheet. Ultimately a filter is applied on a particular data so that when the output file is opened, it should display filtered data by default.
Code to Create Filter in Excel using Java
In this sample code, a filter is applied on one of the columns however you can set filters on multiple columns in Excel based on respective values in that column. Here if you want to save the output file to some other format like XPS, you may refer to the article on how to convert Excel to XPS in Java.
Also, note that no other component or libraries like Interop or MS Excel is required for running the above code.