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 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(number, SortOrder, string[])**) 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(number, SortOrder, string[])**) 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.

todo:image_alt_text

Sample Code

//For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
const AsposeCells = require("aspose.cells.node");
//Load the source Excel file
var wb = new AsposeCells.Workbook("sampleSortData_CustomSortList.xlsx");
//Access first worksheet
var ws = wb.getWorksheets().get(0);
//Specify cell area - sort from A1 to A40
var ca = AsposeCells.CellArea.createCellArea("A1", "A40");
//Create Custom Sort list
var customSortList = ["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, AsposeCells.SortOrder.Ascending, customSortList);
wb.getDataSorter().sort(ws.getCells(), ca);
//Save the output Excel file
wb.save("outputSortData_CustomSortList.xlsx");