资料整理

在 Microsoft Excel 中对数据进行排序

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

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

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

Microsoft Excel 中的排序对话框

待办事项:图片_替代_文本

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

Aspose.Cells 提供了数据分类器用于按升序或降序对数据进行排序的类。该类有一些重要的成员,例如,像这样的方法设置键1 … 设置密钥2设置订单1 … setOrder2.这些成员用于定义排序键并指定键排序顺序。

在实现数据排序之前,您必须定义键并设置排序顺序。该类提供[种类](https://reference.aspose.com/cells/java/com.aspose.cells/datasorter#sort()方法,用于根据工作表中的单元格数据执行数据排序。

种类 方法接受以下参数:

  • Cells, 工作表的单元格。
  • 单元格区域单元格范围。在应用数据排序之前定义单元格区域。

此示例显示如何使用 Aspose.Cells API 对数据进行排序。该示例使用模板文件“Book1.xls”并在第一个工作表中对数据范围 (A1:B14) 的数据进行排序:

此示例使用在 Microsoft Excel 中创建的模板文件“Book1.xls”。

包含数据的模板 Excel 文件

待办事项:图片_替代_文本

执行下面的代码后,数据被适当地排序,正如您从输出的 Excel 文件中看到的那样。

数据排序后输出Excel文件

待办事项:图片_替代_文本

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(DataSorting.class) + "data/";
// Instantiate a new Workbook object.
Workbook workbook = new Workbook(dataDir + "book1.xls");
// Get the workbook datasorter object.
DataSorter sorter = workbook.getDataSorter();
// Set the first order for datasorter object.
sorter.setOrder1(SortOrder.DESCENDING);
// Define the first key.
sorter.setKey1(0);
// Set the second order for datasorter object.
sorter.setOrder2(SortOrder.ASCENDING);
// Define the second key.
sorter.setKey2(1);
// Sort data in the specified data range (CellArea range: A1:B14)
CellArea cellArea = new CellArea();
cellArea.StartRow = 0;
cellArea.StartColumn = 0;
cellArea.EndRow = 13;
cellArea.EndColumn = 1;
sorter.sort(workbook.getWorksheets().get(0).getCells(), cellArea);
// Save the excel file.
workbook.save(dataDir + "DataSorting_out.xls");
// Print message
System.out.println("Sorting Done Successfully");

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

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

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

样本背景文件.xlsx

输出样本背景文件.xlsx

示例代码

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Load the Excel file.
Workbook wb = new Workbook(srcDir + "sampleInlineCharts.xlsx");
// Access the sheet
Worksheet ws = wb.getWorksheets().get(0);
// Set the print area.
ws.getPageSetup().setPrintArea("D2:M20");
// Initialize HtmlSaveOptions
HtmlSaveOptions options = new HtmlSaveOptions();
// Set flag to export print area only
options.setExportPrintAreaOnly(true);
//Save to HTML format
wb.save(outDir + "outputInlineCharts.html",options);

推进主题