データソート

Microsoft Excel でのデータのソート

Microsoft Excel でデータをソートするには:

  1. ソートメニューからデータを選択します。ソートダイアログが表示されます。
  2. ソートオプションを選択します。

一般的に、ソートはリスト上で実行されます。リストは、データが列に表示される連続したグループと定義されます。

Aspose.Cells でのデータのソート

Aspose.Cellsは、昇順または降順でデータをソートするために使用されるDataSorterクラスを提供しています。このクラスには、Key1などの重要なメンバーがあります。これらのメンバーはソートされたキーを定義し、Keyの並べ替えを指定するために使用されます。

データソートを実装する前に、キーを定義してソート順を設定する必要があります。このクラスは、ワークシート内のセルデータに基づいてデータのソートを実行するために使用される Sort メソッドを提供しています。

Sort メソッドは、以下のパラメータを受け入れます:

この例では、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によってAddKey()で背景色に基づいてデータをソートすることができます。指定された色を含むすべてのセルは、SortOrderの設定と残りのセルの順序に従って、上部または下部に配置されます。

これがこの機能のテストにダウンロードできるサンプルファイルです。

sampleBackGroundFile.xlsx

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");

高度なトピック