C#を使用してExcelテーブルのデータをフィルタリングする方法

このトピックでは、C#を使用してExcelテーブルのデータをフィルター処理する方法について必要な詳細を説明します。サンプルコードは、XLSXファイルのC#を使用してExcelでフィルターを追加する方法を示しています。さらに、いくつかの簡単な手順でC#を使用してExcelスプレッドシートに動的フィルターを作成できます。

C#を使用してExcelテーブルのデータをフィルタリングする手順

  1. NuGet.orgからAspose.Cells for .NETパッケージを取得します
  2. Aspose.Cells名前空間をプロジェクトにインポートします
  3. SetLicenseメソッドを使用してLicenseオブジェクトをインスタンス化して設定します
  4. ゼロからWorkbookを作成する
  5. ブックの最初のワークシートにデータを挿入します
  6. AutoFilterの範囲を設定し、カスタムフィルタリングを追加します
  7. フィルタリングされたデータをXLSXファイルに保存

データを動的にフィルタリングするということは、特定の基準をカバーするレコードのみを表示することを意味します。特定の果物(この場合はブドウ)のレコードのみを取得する場合、この例はExcelの自動フィルター機能を示し、C#のExcelでカスタムフィルターを適用する方法を理解するのに役立ちます。

C#を使用してExcelテーブルのデータをフィルタリングするサンプルコード

using System;
using Aspose.Cells;
namespace FilterDataInExcelTable
{
class Program
{
static void Main(string[] args)
{
//Create License object and set it at the start before using any other APIs
Aspose.Cells.License Aspose_Cells_lic = new Aspose.Cells.License();
Aspose_Cells_lic.SetLicense("Aspose.Cells.lic");
//Create an empty Excel workbook
Workbook FilteringDataWorkbook = new Workbook();
//Get the worksheet at first indexed position in the workbook - default worksheet
Worksheet FilteringDataSheet = FilteringDataWorkbook.Worksheets[0];
//Obtain the cells collection from the first sheet
Cells FilteringDataCells = FilteringDataSheet.Cells;
//Put data/values into the cells for the table
FilteringDataCells["A1"].PutValue("Fruits");
FilteringDataCells["B1"].PutValue("Total");
FilteringDataCells["A2"].PutValue("Blueberries");
FilteringDataCells["B2"].PutValue(2500);
FilteringDataCells["A3"].PutValue("Apples");
FilteringDataCells["B3"].PutValue(1100);
FilteringDataCells["A4"].PutValue("Mangoes");
FilteringDataCells["B4"].PutValue(1500);
FilteringDataCells["A5"].PutValue("Grapes");
FilteringDataCells["B5"].PutValue(1200);
FilteringDataCells["A6"].PutValue("Oranges");
FilteringDataCells["B6"].PutValue(3000);
FilteringDataCells["D1"].PutValue("Count:");
//Specify formula to E1 cell - this formula would give you count
FilteringDataCells["E1"].Formula = "=SUBTOTAL(2,B1:B6)";
//Set the range to which the specified autofilters would be applied
FilteringDataSheet.AutoFilter.Range = "A1:B6";
//Now add your desired filter to first column to select your desired data
FilteringDataSheet.AutoFilter.AddFilter(0, "Grapes");
FilteringDataSheet.AutoFilter.Refresh();
//Save Excel XLSX file
FilteringDataWorkbook.Save("FilteredData.xlsx");
}
}
}

コードセグメント(上記)は、空白のワークブックをインスタンス化してから、最初のワークシートのセルの範囲にデータを挿入します。 C#コードは、Excelの自動フィルター範囲を設定します。 Excelスプレッドシートにカスタムフィルターを追加または適用します。最後に、フィルタリングされたデータをディスク上のXLSXファイルに保存します。 C#でExcel円グラフを作成する方法トピックにも興味があるかもしれません。

 日本語