数据排序
在 Microsoft Excel 中排序数据
要在 Microsoft Excel 中排序数据:
- 从“排序”菜单中选择“数据”。将显示“排序”对话框。
- 选择排序选项。
通常,排序是针对一个列表执行的 - 定义为一组连续的数据,数据以列显示。
使用 Aspose.Cells 进行数据排序
Aspose.Cells 提供了用于按升序或降序对数据进行排序的 DataSorter 类。该类具有一些重要成员,例如 Key1 … Key3 和 Order1 … Order3 等属性。这些成员用于定义排序键并指定键排序顺序。
在执行数据排序之前,您必须定义关键字并设置排序顺序。该类提供了 Sort 方法,用于根据工作表中的单元格数据执行数据排序。
Sort 方法接受以下参数:
- Aspose.Cells.Cells,基础工作表的单元格。
- Aspose.Cells.CellArea,单元格范围。在应用数据排序前定义单元格区域。
此示例使用在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,可以使用SortOnType.CellColor在AddKey()中对基于背景颜色的数据进行排序。AddKey()中包含指定颜色的所有单元格,按照SortOrder设置的方式放置在顶部或底部,其余单元格的顺序保持不变。
以下是可以下载以进行此功能测试的样本文件:
outputsampleBackGroundFile.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"); |