How to Edit Excel File in C++

In this example, we will explore how to edit Excel file in C++. You can edit Excel file programmatically in C++ using simple API interface that can be used both in Microsoft Windows and Linux etc.

Steps to Edit Excel File in C++

  1. Add Aspose.Cells.Cpp with NuGet package Manager tool
  2. Add a reference to Aspose::Cells namespace
  3. Create instance of Workbook object to load Excel file for editing
  4. Access the cells A1 and C1 inside worksheet and set data and formula string respectively
  5. Calculate the formula for Workbook
  6. Save the output workbook with formula to XLSX in C++

The following example is used to access the workbook and update Excel file in C++ very quickly and easily using few API calls. Using C++, you can set any content data to Excel cells programmatically like Date, Percentage, Numeric or any other value.

Code to Edit Excel File in C++

#pragma once
#include "Aspose.Cells.h"
class ExcelFileEditing
{
void UpdateCellInExcel()
{
// Add Aspose.Cells for C++ API License
intrusive_ptr<License> CellRenderingLicense = new License();
CellRenderingLicense->SetLicense(new String("CPP.Aspose.Total.lic"));
// Instantiate the Workbook class object to load Excel file for editing
intrusive_ptr<IWorkbook> WbWithDataAndFormula = Factory::CreateIWorkbook();
// Access cell A1 from a first worksheet to set data
intrusive_ptr <ICell> DataCell = WbWithDataAndFormula->GetIWorksheets()->GetObjectByIndex(0)->
GetICells()->GetObjectByIndex(new String("A1"));
// Set some value in cell
DataCell->PutValue(100);
// Access cell C1 from first worksheet to update formula
intrusive_ptr <ICell> ForumulCell = WbWithDataAndFormula->GetIWorksheets()->GetObjectByIndex(0)->
GetICells()->GetObjectByIndex(new String("C1"));
// Update the formula for selected cell
ForumulCell->SetFormula(new String("=Sum(A1,A20)"));
// Calculate the workbook after formula is updated
WbWithDataAndFormula->CalculateFormula();
// Save the output workbook with formula to XLSX
WbWithDataAndFormula->Save(new String("WorkbookWithFormula.xlsx"));
}
};

This entire process of editing Excel file in C++ is achieved with no dependence on Microsoft Office or Interop. At this point, if you even want to save the Excel file as PDF, you can explore example How to Convert Excel to PDF using C++.

 English