在本教程中,我们将学习如何使用 C++ 在 XLSX 文件中添加过滤器。您可以在 C++ 中以编程方式在 Microsoft Windows、Linux 等上的 Excel 工作表中插入过滤器。
使用 C++ 在 XLSX 文件中添加过滤器的步骤
- 使用 NuGet 包管理器插件安装 Aspose.Cells.Cpp 包
- 添加对 Aspose::Cells 命名空间的引用
- 初始化 Workbook 类对象以实例化新的 Excel 工作簿
- 将样本值插入单元格
- 设置过滤数据的公式和范围
- 使用 AddFilter 方法将过滤器包含到列中
- 使用 C++ 过滤数据后保存输出 Excel 文件
在以下示例中,您将探索如何使用 C++ 在 Excel 文件中创建过滤器。只需执行几个步骤,即可初始化一个空工作表并 使用 C++ 在 Excel 文件中应用过滤器。
在 C++ 中的 Excel 文件中添加过滤器的代码
#pragma once | |
#include "Aspose.Cells.h" | |
class ExcelFilterData | |
{ | |
void FilterExcelData() | |
{ | |
// Set the license for Aspose.Cells API for filtering data | |
intrusive_ptr<License> CellFilterLicense = new License(); | |
CellFilterLicense->SetLicense(new String("Aspose.Total.lic")); | |
// Instantiate the Workbook object to create empty file to filter out the data | |
intrusive_ptr<IWorkbook> FilterWorkbook = Factory::CreateIWorkbook(); | |
// Access the first worksheet using 0 index for filtering data | |
intrusive_ptr<IWorksheet> FilterWorksheet = FilterWorkbook->GetIWorksheets()->GetObjectByIndex(0); | |
// Adding sample data and values to cells for filtering | |
FilterWorksheet->GetICells()->GetObjectByIndex(new String("A1"))->PutValue("Fruits"); | |
FilterWorksheet->GetICells()->GetObjectByIndex(new String("B1"))->PutValue("Total"); | |
FilterWorksheet->GetICells()->GetObjectByIndex(new String("A2"))->PutValue("Blueberries"); | |
FilterWorksheet->GetICells()->GetObjectByIndex(new String("B2"))->PutValue("2500"); | |
FilterWorksheet->GetICells()->GetObjectByIndex(new String("A3"))->PutValue("Apples"); | |
FilterWorksheet->GetICells()->GetObjectByIndex(new String("B3"))->PutValue("1100"); | |
FilterWorksheet->GetICells()->GetObjectByIndex(new String("A4"))->PutValue("Mangoes"); | |
FilterWorksheet->GetICells()->GetObjectByIndex(new String("B4"))->PutValue("1500"); | |
FilterWorksheet->GetICells()->GetObjectByIndex(new String("A5"))->PutValue("Grapes"); | |
FilterWorksheet->GetICells()->GetObjectByIndex(new String("B5"))->PutValue("1200"); | |
FilterWorksheet->GetICells()->GetObjectByIndex(new String("A6"))->PutValue("Oranges"); | |
FilterWorksheet->GetICells()->GetObjectByIndex(new String("A5"))->PutValue("3000"); | |
FilterWorksheet->GetICells()->GetObjectByIndex(new String("B5"))->PutValue("Count:"); | |
// Set formula for filtering data | |
FilterWorksheet->GetICells()->GetObjectByIndex(new String("E1"))->SetFormula(new String("=SUBTOTAL(2,B1:B6)")); | |
// Set the range for applying AutoFilter | |
FilterWorksheet->GetIAutoFilter()->SetRange(new String("A1:B6")); | |
// Add an AutoFilter to a specific column | |
FilterWorksheet->GetIAutoFilter()->AddFilter(0 , new String("Grapes")); | |
FilterWorksheet->GetIAutoFilter()->Refresh(); | |
// Save the output Excel file with filtered data | |
FilterWorkbook->Save(new String ("FilterOutput.xlsx")); | |
} | |
}; |
您可以通过将示例数据和值插入单元格来使用 C++ 在 Excel 文件中创建过滤器。您无需安装 MS Excel 或任何其他应用程序即可轻松过滤 Excel 文件中的数据。在前面的示例中,我们学习了 如何在 C++ 中将 Excel 文件转换为 CSV,它解释了从 Excel 文件到 CSV 文件的转换。