在这个例子中,我们将探索如何在 C++ 中编辑 Excel 文件。您可以使用可在 Microsoft Windows 和 Linux 等中使用的简单 API 接口在 C++ 中以编程方式编辑 Excel 文件。
在 C++ 中编辑 Excel 文件的步骤
- 使用 NuGet 包管理器工具添加 Aspose.Cells.Cpp
- 添加对 Aspose::Cells 命名空间的引用
- 创建 Workbook 对象的实例以加载 Excel 文件进行编辑
- 访问工作表内的单元格 A1 和 C1 并分别设置数据和公式字符串
- 计算工作簿的公式
- 将带有公式的输出工作簿保存到 C++ 中的 XLSX
以下示例用于使用少量 API 调用非常快速、轻松地访问工作簿和 *更新 C++ 中的 Excel 文件。使用 C++,您可以以编程方式将任何内容数据设置为 Excel 单元格,例如日期、百分比、数字或任何其他值。
用 C++ 编辑 Excel 文件的代码
#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")); | |
} | |
}; |
用 C++ 编辑 Excel 文件的整个过程是在不依赖 Microsoft Office 或 Interop 的情况下实现的。此时,如果您甚至想将 Excel 文件另存为 PDF,您可以探索示例 如何使用 C++ 将 Excel 转换为 PDF。