Manage Workbook with C++
Creating a New Workbook
To create a new workbook:
- Create an instance of the Workbook class.
- Add worksheets to the workbook using the WorksheetCollection class.
- Save the workbook using the Save method.
#include <Aspose.Cells.h>
int main() {
Aspose::Cells::Startup();
// Create a new workbook
Aspose::Cells::Workbook workbook;
// Add a worksheet to the workbook
workbook.GetWorksheets().Add();
// Save the workbook
workbook.Save("output.xlsx");
Aspose::Cells::Cleanup();
return 0;
}
Opening an Existing Workbook
To open an existing workbook:
- Create an instance of the Workbook class and pass the file path to the constructor.
- Access the worksheets using the WorksheetCollection class.
- Modify the workbook as needed.
- Save the workbook using the Save method.
#include <Aspose.Cells.h>
int main() {
Aspose::Cells::Startup();
Aspose::Cells::Workbook workbook("input.xlsx");
auto worksheet = workbook.GetWorksheets().Get(0);
worksheet.GetCells().Get(0, 0).SetValue("Hello, World!");
workbook.Save("output.xlsx");
Aspose::Cells::Cleanup();
return 0;
}
Managing Worksheets
Aspose.Cells for C++ provides a wide range of methods for managing worksheets, including adding, removing, and renaming worksheets.
Adding a Worksheet
To add a new worksheet:
- Access the WorksheetCollection class from the workbook.
- Use the Add method to add a new worksheet.
#include <Aspose.Cells.h>
int main() {
Aspose::Cells::Startup();
// Create a new workbook
Aspose::Cells::Workbook workbook;
// Add a new worksheet
workbook.GetWorksheets().Add("NewSheet");
// Save the workbook
workbook.Save("output.xlsx");
Aspose::Cells::Cleanup();
return 0;
}
Removing a Worksheet
To remove a worksheet:
- Access the WorksheetCollection class from the workbook.
- Use the RemoveAt method to remove a worksheet by index.
#include <Aspose.Cells.h>
int main() {
Aspose::Cells::Startup();
// Open an existing workbook
Aspose::Cells::Workbook workbook("input.xlsx");
// Remove the first worksheet
workbook.GetWorksheets().RemoveAt(0);
// Save the workbook
workbook.Save("output.xlsx");
Aspose::Cells::Cleanup();
return 0;
}
Renaming a Worksheet
To rename a worksheet:
#include <Aspose.Cells.h>
int main() {
Aspose::Cells::Startup();
Aspose::Cells::Workbook workbook("input.xlsx");
auto worksheet = workbook.GetWorksheets().Get(0);
worksheet.SetName("RenamedSheet");
workbook.Save("output.xlsx");
Aspose::Cells::Cleanup();
return 0;
}
Conclusion
Aspose.Cells for C++ provides a comprehensive set of tools for managing workbooks and worksheets. Whether you need to create a new workbook, open an existing one, or manipulate worksheets, Aspose.Cells makes it easy to work with Excel files programmatically.