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
import com.gembox.spreadsheet.*;

import java.util.Random;

class Program {

    public static void main(String[] args) throws java.io.IOException {
        // If using Professional version, put your serial key below.

        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();


Want more?

Next example GitHub

Check the next example or select an example from the menu. You can also download our examples from the GitHub.

Like it?

Download Buy

If you want to try the GemBox.Spreadsheet for Java yourself, you can download the free version. It delivers the same performance and set of features as the professional version, but with some operations limited. To remove the limitation, you need to purchase a license.