// Create a new workbook Workbook workbook = new Workbook(); IWorksheet ws = workbook.getWorksheets().get(0); ws.setName("SORT"); ws.getRange("$B$1").setValue( "Use the SORT function to sort a range or array in ascending or descending order. Syntax: SORT(array,[sort_index],[sort_order],[by_col])"); ws.getRange("$E$2:$E$3") .setValue(new Object[][] { { "Sort data in descending order: SORT(C4:C13,1,-1)" }, { "Units" } }); ws.getRange("$C$3:$C$13").setValue(new Object[][] { { "Units" }, { 622d }, { 961d }, { 691d }, { 445d }, { 378d }, { 483d }, { 650d }, { 783d }, { 142d }, { 404d } }); ws.getRange("$H$15:$H$16") .setValue(new Object[][] { { "Sort range C17:F32 by Units: SORT(C17:F32,4,1,FALSE)" }, { "Region" } }); ws.getRange("$C$16:$F$32") .setValue(new Object[][] { { "Region", "Sales Rep", "Product", "Units" }, { "East", "Tom", "Apple", 6380d }, { "West", "Fred", "Grape", 5619d }, { "North ", "Amy", "Pear", 4565d }, { "South", "Sal", "Banana", 5323d }, { "East", "Fritz", "Apple", 4394d }, { "West", "Sravan", "Grape", 7195d }, { "North ", "Xi", "Pear", 5231d }, { "South", "Hector", "Banana", 2427d }, { "East", "Tom", "Banana", 4213d }, { "West", "Fred", "Pear", 3239d }, { "North ", "Amy", "Grape", 6420d }, { "South", "Sal", "Apple", 1310d }, { "East", "Fritz", "Banana", 6274d }, { "West", "Sravan", "Pear", 4894d }, { "North ", "Xi", "Grape", 7580d }, { "South", "Hector", "Apple", 9814d } }); ws.getRange("$I$16:$K$16").setValue(new Object[][] { { "Sales Rep", "Product", "Units" } }); // Apply table style. ITable table = ws.getTables().add(ws.getRange("C3:C13"),true); ITable table1 = ws.getTables().add(ws.getRange("E3:E13"),true); ITable table2 = ws.getTables().add(ws.getRange("C16:F32"),true); ITable table3 = ws.getTables().add(ws.getRange("H16:K32"),true); table.convertToRange(); table1.convertToRange(); table2.convertToRange(); table3.convertToRange(); ws.getRange("$E$4").setFormula2("=SORT(C4:C13,1,-1)"); ws.getRange("$H$17").setFormula2("=SORT(C17:F32,4,1,FALSE)"); ws.getRange("$F$17:$F$32,$K$17:$K$32").setNumberFormat("#,##0"); // Save to an excel file workbook.save("SortFunction.xlsx");