资料整理

在 Microsoft Excel 中对数据进行排序

对 Microsoft Excel 中的数据进行排序:

  1. 选择数据来自种类菜单。将显示排序对话框。
  2. 选择一个排序选项。

通常,排序是在列表上执行的 - 定义为一组连续的数据,其中数据显示在列中。

使用 Aspose.Cells 对数据进行排序

Aspose.Cells 提供了数据分类器用于按升序或降序对数据进行排序的类。该类有一些重要的成员,例如 Key1 … Key3 和 Order1 … Order3 等属性。这些成员用于定义排序键并指定键排序顺序。

在实现数据排序之前,您必须定义键并设置排序顺序。该类提供种类用于根据工作表中的单元格数据执行数据排序的方法。

种类方法接受以下参数:

此示例使用在 Microsoft Excel 中创建的模板文件“Book1.xls”。执行下面的代码后,数据被适当地排序。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Instantiate a new Workbook object.
// Load a template file.
Workbook workbook = new Workbook(dataDir + "book1.xls");
// Get the workbook datasorter object.
DataSorter sorter = workbook.DataSorter;
// Set the first order for datasorter object.
sorter.Order1 = Aspose.Cells.SortOrder.Descending;
// Define the first key.
sorter.Key1 = 0;
// Set the second order for datasorter object.
sorter.Order2 = Aspose.Cells.SortOrder.Ascending;
// Define the second key.
sorter.Key2 = 1;
// Create a cells area (range).
CellArea ca = new CellArea();
// Specify the start row index.
ca.StartRow = 0;
// Specify the start column index.
ca.StartColumn = 0;
// Specify the last row index.
ca.EndRow = 13;
// Specify the last column index.
ca.EndColumn = 1;
// Sort data in the specified data range (A1:B14)
sorter.Sort(workbook.Worksheets[0].Cells, ca);
// Save the excel file.
workbook.Save(dataDir + "output.out.xls");

使用背景颜色对数据进行排序

Excel 提供了根据背景颜色对数据进行排序的功能。使用 Aspose.Cells 使用 DataSorter 提供相同的功能,其中排序类型.CellColor 可用于添加密钥()根据背景颜色对数据进行排序。包含指定颜色的所有单元格添加密钥()函数根据 SortOrder 设置放置在顶部或底部,其余单元格的顺序根本没有改变。

以下是可以下载以测试此功能的示例文件:

样本背景文件.xlsx

输出样本背景文件.xlsx

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Create a workbook object and load template file
Workbook workbook = new Workbook(sourceDir + "CellsNet46500.xlsx");
// Instantiate data sorter object
DataSorter sorter = workbook.DataSorter;
// Add key for second column for red color
sorter.AddKey(1, SortOnType.CellColor, SortOrder.Descending, Color.Red);
// Sort the data based on the key
sorter.Sort(workbook.Worksheets[0].Cells, CellArea.CreateCellArea("A2", "C6"));
// Save the output file
workbook.Save(outputDir + "outputSortData_CustomSortList.xlsx");

推进主题