Sort Data in Column with Custom Sort List
Possible Usage Scenarios
You can sort data in the column using a custom list. This can be done using DataSorter.AddKey(int key, SortOrder order, String customList) method. However, this method works only if the items in the custom list do not have commas inside them. If they have commas like “USA, US”, “China, CN” etc., then you must use DataSorter.AddKey(int key, SortOrder order, String customList) method. Here, the last parameter is not String but an Array of Strings.
Sort Data in Column with Custom Sort List
The following sample code explains how to use DataSorter.AddKey(int key, SortOrder order, String[] customList) method to sort data with custom sort list. Please see the sample Excel file used in this code and output Excel file generated by it. The following screenshot shows the effect of the code on the sample Excel file on execution.
Sample Code
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
//Load the source Excel file | |
Workbook wb = new Workbook(srcDir + "sampleSortData_CustomSortList.xlsx"); | |
//Access first worksheet | |
Worksheet ws = wb.getWorksheets().get(0); | |
//Specify cell area - sort from A1 to A40 | |
CellArea ca = CellArea.createCellArea("A1", "A40"); | |
//Create Custom Sort list | |
String[] customSortList = new String[] { "USA,US", "Brazil,BR", "China,CN", "Russia,RU", "Canada,CA" }; | |
//Add Key for Column A, Sort it in Ascending Order with Custom Sort List | |
wb.getDataSorter().addKey(0, SortOrder.ASCENDING, customSortList); | |
wb.getDataSorter().sort(ws.getCells(), ca); | |
//Save the output Excel file | |
wb.save(outDir + "outputSortData_CustomSortList.xlsx"); |