Sort Data in Column with Custom Sort List with C++
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 Method (Int32, 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 Method (Int32, 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.
Sample Code
#include <iostream>
#include "Aspose.Cells.h"
using namespace Aspose::Cells;
int main()
{
Aspose::Cells::Startup();
// Source directory path
U16String srcDir(u"..\\Data\\01_SourceDirectory\\");
// Output directory path
U16String outDir(u"..\\Data\\02_OutputDirectory\\");
// Load the source Excel file
Workbook wb(srcDir + u"sampleSortData_CustomSortList.xlsx");
// Access first worksheet
Worksheet ws = wb.GetWorksheets().Get(0);
// Specify cell area - sort from A1 to A40
CellArea ca = CellArea::CreateCellArea(u"A1", u"A40");
// Create Custom Sort list
Vector<U16String> customSortList = { u"USA,US", u"Brazil,BR", u"China,CN", u"Russia,RU", u"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 + u"outputSortData_CustomSortList.xlsx");
std::cout << "Data sorted successfully with custom sort list!" << std::endl;
Aspose::Cells::Cleanup();
}