Como criar um arquivo do Excel usando C++

Neste tutorial, aprenderemos como criar arquivo Excel usando C++. Você pode criar um arquivo XLSX ou XLS usando C++ no MS Windows ou Linux programaticamente em C++.

Etapas para criar um arquivo do Excel usando C++

  1. Configure o pacote Aspose.Cells.Cpp com a ferramenta gerenciador de pacotes NuGet
  2. Adicione a referência ao namespace Aspose::Cells
  3. Inicialize o objeto Class Workbook para instanciar uma pasta de trabalho do Excel em branco
  4. Insira valores de amostra nas células do arquivo Excel
  5. Salve o arquivo Excel de saída após inserir dados usando C++

No exemplo a seguir, você explorará como criar um arquivo Excel usando C++. Inicialize uma pasta de trabalho vazia e insira valores de amostra nas células simplesmente seguindo algumas etapas.

Código para criar arquivo do Excel em C++

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

Você pode gerar arquivo do Excel usando C++ criando uma pasta de trabalho vazia e inserindo dados e valores de amostra nas células. Você não precisa instalar o MS Excel ou qualquer outro aplicativo para gerar o arquivo excel com este trecho de código. No exemplo anterior, aprendemos Como adicionar filtro no arquivo XLSX usando C++ que explica como adicionar um filtro no arquivo XLSX.

 Português