Java: Sort Data in Excel

The sort function in Excel allows you to arrange the text in alphabetical order, sort the numbers from smallest to largest or largest to smallest, and dates from oldest to latest or latest to oldest, etc. In this article, you will learn how to programmatically sort numbers in a cell range using Spire.XLS for Java.

Install Spire.XLS for Java

First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls</artifactId>
        <version>14.3.2</version>
    </dependency>
</dependencies>
    

Sort Data in Excel

The detailed steps are as follows:

  • Create a Workbook instance and load a sample Excel document using Workbook.loadFromFile() method.
  • Get a specified worksheet using Workbook.getWorksheets().get() method.
  • Get a sort fields collection using Workbook.getDataSorter().getSortColumns() method, and then specify the column that need to be sorted and the sort mode in the collection using SortColumns.add() method.
  • Sort the data in the specified cell range of the collection using Workbook.getDataSorter().sort() method.
  • Save the document to file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

public class SortData {

    public static void main(String[] args) {

        //Create a Workbook instance
        Workbook workbook = new Workbook();

        //Load the sample Excel document
        workbook.loadFromFile("sample.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Specify the column that need to be sorted and the sort mode (ascending or descending)
        workbook.getDataSorter().getSortColumns().add(0, SortComparsionType.Values, OrderBy.Ascending);

        //Sort data in the specified cell range
        workbook.getDataSorter().sort(sheet.getCellRange("A1:D10"));

        //Save the document to file
        workbook.saveToFile("SortData.xlsx", ExcelVersion.Version2013);
    }
}

Java: Sort Data in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.