在本教程中,我们将学习如何使用 C++ 创建 Excel 文件。您可以使用 C++ 在 MS Windows 或 Linux 上以 C++ 编程方式创建 XLSX 或 XLS 文件。
使用 C++ 创建 Excel 文件的步骤
- 使用 NuGet 包管理器工具配置 Aspose.Cells.Cpp 包
- 添加对 Aspose::Cells 命名空间的引用
- 初始化 Workbook 类对象以实例化一个空白 Excel 工作簿
- 将样本值插入 Excel 文件的单元格
- 使用 C++ 插入数据后保存输出 Excel 文件
在以下示例中,您将探索如何使用 C++ 制作 Excel 文件。只需执行几个步骤,即可初始化一个空工作簿并将示例值插入到单元格中。
在 C++ 中创建 Excel 文件的代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include "Aspose.Cells.h" | |
class ExcelWorkbook | |
{ | |
void CreateExcelWorkbook() | |
{ | |
// Set the license for Aspose.Cells API for creating workbook | |
intrusive_ptr<License> CellCreateLicense = new License(); | |
CellCreateLicense->SetLicense(new String("Aspose.Total.lic")); | |
// Instantiate the Workbook object to create an empty XLSX file | |
intrusive_ptr<IWorkbook> CreateWorkbook = Factory::CreateIWorkbook(); | |
//Accessing a worksheet using its index for inserting data | |
intrusive_ptr<IWorksheet> CreateWorksheet = CreateWorkbook->GetIWorksheets()->GetObjectByIndex(0); | |
// Adding sample data and values to cells for filtering | |
CreateWorksheet->GetICells()->GetObjectByIndex(new String("A1"))->PutValue("Customers Report"); | |
CreateWorksheet->GetICells()->GetObjectByIndex(new String("A2"))->PutValue("C_ID"); | |
CreateWorksheet->GetICells()->GetObjectByIndex(new String("B2"))->PutValue("C_Name"); | |
CreateWorksheet->GetICells()->GetObjectByIndex(new String("A3"))->PutValue("C001"); | |
CreateWorksheet->GetICells()->GetObjectByIndex(new String("B3"))->PutValue("Customer1"); | |
CreateWorksheet->GetICells()->GetObjectByIndex(new String("A4"))->PutValue("C002"); | |
CreateWorksheet->GetICells()->GetObjectByIndex(new String("B4"))->PutValue("Customer2"); | |
CreateWorksheet->GetICells()->GetObjectByIndex(new String("A5"))->PutValue("C003"); | |
CreateWorksheet->GetICells()->GetObjectByIndex(new String("B5"))->PutValue("Customer3"); | |
CreateWorksheet->GetICells()->GetObjectByIndex(new String("A6"))->PutValue("C004"); | |
CreateWorksheet->GetICells()->GetObjectByIndex(new String("B6"))->PutValue("Customer4"); | |
// Save the output Excel file with inserted data | |
CreateWorkbook->Save(new String ("WorkbookOutput.xlsx")); | |
} | |
}; | |
您可以通过创建空工作簿并将示例数据和值插入单元格来使用 C++ 生成 Excel 文件。您无需安装 MS Excel 或任何其他应用程序即可使用此代码段生成 excel 文件。在前面的示例中,我们学习了 如何使用 C++ 在 XLSX 文件中添加过滤器,它解释了在 XLSX 文件中添加过滤器。