在包含自定义排序列表的列中排序数据

可能的使用场景

您可以使用DataSorter.AddKey(int key, SortOrder order, String customList)方法对列中的数据使用自定义列表进行排序。然而,该方法仅在自定义列表中的项目不包含逗号时才有效。如果它们包含逗号,如"美国,US",“中国,CN"等,则必须使用**DataSorter.AddKey Method(Int32, SortOrder, String[])方法。在这里,最后一个参数不是String,而是字符串数组。

使用自定义排序列表对列中的数据进行排序

以下示例代码解释了如何使用**DataSorter.AddKey Method(Int32, SortOrder, String[])方法对数据使用自定义排序列表进行排序。请参阅此代码中使用的示例Excel文件和其生成的输出Excel文件。以下截图展示了代码对示例Excel文件执行后的效果。

todo:image_alt_text

示例代码

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
//Load the source Excel file
Workbook wb = new Workbook(sourceDir + "sampleSortData_CustomSortList.xlsx");
//Access first worksheet
Worksheet ws = wb.Worksheets[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.DataSorter.AddKey(0, SortOrder.Ascending, customSortList);
wb.DataSorter.Sort(ws.Cells, ca);
//Save the output Excel file
wb.Save(outputDir + "outputSortData_CustomSortList.xlsx");