This tutorial is a quick guide to merge cells in Excel using C++. It explains precise and simple steps in addition to a C++ code snippet. Using C++ Excel cell merge operation is performed and then the output file can be saved in XLSX or XLS format.
Steps to Merge Cells in Excel using C++
- Add the reference to Aspose.Cells.Cpp in your project using the NuGet Package Manager
- Initialize an empty Excel file with the Workbook class object for merging cells
- Access the first worksheet and initialize a Cells class instance
- Perform the cells merge operation and insert a sample value
- Write the output Excel workbook containing the merged cell
You can notice the simple steps which are based on C++, excel merge cells operation can be performed easily with a few API calls. It lets you create a new Excel file from scratch as well as an existing Excel file can also be used as input.
Code to Merge Cells in Excel using C++
#pragma once | |
#include "Aspose.Cells.h" | |
class MergeCellsInExcel | |
{ | |
public: void MergeCellsInExcelInCPlusCPlus() | |
{ | |
// Set the license to avoid watermark in the output Excel file after merging cells | |
intrusive_ptr<License> MergeCellsInExcelLicense = new License(); | |
MergeCellsInExcelLicense->SetLicense(new String("Aspose.Cells.lic")); | |
// Create an Excel file | |
intrusive_ptr<IWorkbook> workbook = Factory::CreateIWorkbook(); | |
// Get access to first worksheet | |
intrusive_ptr<IWorksheet> worksheet = workbook->GetIWorksheets()->GetObjectByIndex(0); | |
// Create a Cells object | |
intrusive_ptr<ICells> cells = worksheet->GetICells(); | |
// Merge cells | |
cells->Merge(5, 2, 2, 3); | |
// Put data in the cell | |
cells->GetObjectByIndex(5, 2)->PutValue((StringPtr)new String("Sample value")); | |
// Save the Excel file | |
workbook->Save(new String("MergeCells.xlsx")); | |
} | |
}; |
This code snippet initializes an excel worksheet, and then merge cells function is performed on specific cells by using their index values. Moreover, it also inserts a sample value as a string into the merged cell with the PutValue method. Finally, we can write the output file to a stream or the disk as per the application structure.
In this article, we have explored how to merge cells in Excel using C++ without needing to install the MS Excel application. However, if you want to learn Excel to HTML conversion in C++, refer to the article on how to convert Excel to HTML in C++.