DEV Community

CodeSharing
CodeSharing

Posted on

Sort Excel Data Using Java

Data sorting in Excel is to sort one or more columns of unordered data according to different needs, which helps to display the data in a more organized way and also helps people find the required data faster. This article will demonstrate how to sort data within a cell range using Free Spire.XLS for Java.

Installation
Method 1: Download the free Java library and unzip it, then add the Spire.Xls.jar file to your project as dependency.

Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>3.9.1</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Sample Code

import com.spire.xls.*;

public class SortData {

    public static void main(String[] args) {

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

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

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

        //Specify the column index and the sort mode. The column index starts from 0.
        workbook.getDataSorter().getSortColumns().add(0, SortComparsionType.Values, OrderBy.Ascending);

        //Specify the range to sort
        workbook.getDataSorter().sort(sheet.getCellRange("A1:D10"));

        //Save the document
        workbook.saveToFile("SortData.xlsx", ExcelVersion.Version2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

Results
Alt Text

Top comments (0)