ワークシートデータのソート

ワークシートデータのソート

Aspose.Cells.GridDesktop の API を使用してワークシート内のデータをソートするには、以下の手順に従ってください:

  • まず、CellRange のグローバルオブジェクトを作成し、クラスのスコープ内でいつでもアクセスできるようにします
  • GridDesktopSelectedCellRangeChanged イベントのイベントハンドラを作成します。SelectedCellRangeChanged イベントは、ユーザーによって選択されたセルの範囲が変更されるたびにトリガーされます。たとえば、ユーザーがデータを含むセルを選択した場合、その選択範囲が変更されるたびにこのイベントがトリガーされます。
  • イベントハンドラは CellRange オブジェクトを提供し、このオブジェクトはユーザーによって選択されたセルの更新された範囲を提供します。したがって、このイベントハンドラ内で、この更新されたセル範囲をグローバル CellRange オブジェクトに割り当てます。これにより、コードの他の部分でもそれを使用できるようになります。セル範囲を失わないようにするために、イベントハンドラコードを条件の中に記述します
  • これでワークシートデータをソートするコードを記述できます。まず、所望のワークシートにアクセスします
  • データをソートするセルの範囲を保持する SortRange オブジェクトを作成します。SortRange のコンストラクタでは、ワークシート、開始行と列のインデックス、ソートする行数と列数、ソートの方向(上から下へまたは左から右へなど)などを指定できます。
  • ここで、SortRange オブジェクトの Sort メソッドを呼び出してデータをソートします。Sort メソッドでは、ソートする列または行のインデックス、ソートの順序(昇順 または 降順 など)を指定できます
  • 最後に、GridDesktopInvalidate メソッドを呼び出してセルを再描画します。

以下の例では、列内のデータをソートする方法について示しています。

CellRange のグローバルオブジェクトと GridDesktopSelectedCellRangeChanged イベントを作成します。以下のコードを記述します。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Creating global variable of CellRange
CellRange range;
private void gridDesktop1_SelectedCellRangeChanged(object sender, Aspose.Cells.GridDesktop.CellRangeEventArgs e)
{
// Checking if the range of cells is not empty
if ((e.CellRange.EndColumn - e.CellRange.StartColumn > 0) ||
(e.CellRange.EndRow - e.CellRange.StartRow > 0))
{
// Assigning the updated CellRange to global variable
range = e.CellRange;
}
}

さて、昇順ソートメソッドを記述します。昇順ソートのボタンを作成し、そのClickイベント内に以下のコードを記述します。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Accessing a worksheet that is currently active
Worksheet sheet = gridDesktop1.GetActiveWorksheet();
// Creating SortRange object
SortRange sr = new SortRange(sheet, range.StartRow,
range.StartColumn, range.EndRow - range.StartRow + 1,
range.EndColumn - range.StartColumn + 1,
SortOrientation.SortTopToBottom, true);
// Sorting data in the specified column in ascending order
sr.Sort(range.StartColumn, Aspose.Cells.GridDesktop.SortOrder.Ascending);
// Redrawing cells of the Grid
gridDesktop1.Invalidate();

最後に、降順ソート機能を実現するためのコードを記述します。降順ソートボタンを作成し、そのClickイベント内に以下のコードを記述します。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Accessing a worksheet that is currently active
Worksheet sheet = gridDesktop1.GetActiveWorksheet();
// Creating SortRange object
SortRange sr = new SortRange(sheet, range.StartRow, range.StartColumn,
range.EndRow - range.StartRow + 1,
range.EndColumn - range.StartColumn + 1,
SortOrientation.SortTopToBottom, true);
// Sorting data in the specified column in descending order
sr.Sort(range.StartColumn, Aspose.Cells.GridDesktop.SortOrder.Descending);
// Redrawing cells of the Grid
gridDesktop1.Invalidate();