Excel Sorting

Following example shows how to sort values in a specific cell range of a worksheet.

Sorted cells are written to all output file formats. The active ExcelWorksheet.getSort is written only to XLSX file format.

Screenshot of Excel sort applied with GemBox.Spreadsheet for Java
Screenshot of Excel sort applied with GemBox.Spreadsheet for Java
import com.gembox.spreadsheet.*;

import java.util.Random;

class Program {

    public static void main(String[] args) throws java.io.IOException {
        // If using the Professional version, put your serial key below.
        SpreadsheetInfo.setLicense("FREE-LIMITED-KEY");

        ExcelFile workbook = new ExcelFile();
        ExcelWorksheet worksheet = workbook.addWorksheet("Sorting");

        Random rnd = new Random();

        worksheet.getCell(0, 0).setValue("Sorted numbers");
        worksheet.getCells().getSubrangeAbsolute(0, 0, 0, 1).setMerged(true);
        for (int i = 1; i < 10; i++)
            worksheet.getCell(i, 0).setValue(rnd.nextInt(99) + 1);

        worksheet.getCells().getSubrangeAbsolute(1, 0, 10, 0).sort(false).by(0).apply();

        worksheet.getCell(0, 2).setValue("Sorted strings");
        worksheet.getCells().getSubrangeAbsolute(0, 2, 0, 3).setMerged(true);
        worksheet.getCell(1, 2).setValue("John");
        worksheet.getCell(2, 2).setValue("Jennifer");
        worksheet.getCell(3, 2).setValue("Toby");
        worksheet.getCell(4, 2).setValue("Chloe");

        worksheet.getCells().getSubrangeAbsolute(1, 2, 4, 2).sort(false).by(0).apply();

        worksheet.getCell(0, 4).setValue("Sorted by column E and after that by column F");
        worksheet.getCells().getSubrangeAbsolute(0, 4, 0, 8).setMerged(true);
        for (int i = 1; i < 10; i++)
        {
            worksheet.getCell(i, 4).setValue(rnd.nextInt(3) + 1);
            worksheet.getCell(i, 5).setValue(rnd.nextInt(10));
        }

        // Sort by column E ascending and then by column F descending.
        // These sort settings will be saved to output XLSX file because they are active (parameter value is true).
        worksheet.getCells().getSubrangeAbsolute(1, 4, 10, 5).sort(true).by(0).by(1, true).apply();

        workbook.save("Sorting.%OutputFileType%");
    }
}

See also


Next steps

GemBox.Spreadsheet for Java is a component that enables you to read, write, edit and convert spreadsheet files from your applications using one simple API.

Download Buy