管理工作表

Aspose.Cells提供了一个Workbook类,表示一个Excel文件。Workbook类包含一个Worksheets集合,允许访问Excel文件中的每个工作表。

一个工作表由Worksheet类表示。Worksheet类提供了一系列方法来管理工作表。

向新的Excel文件添加工作表

要通过程序创建新的Excel文件:

  1. 创建 Worksheet 类的对象。
  2. 调用 WorksheetCollection 集合的 Add 方法。空工作表会自动添加到Excel文件. 可以通过向 WorksheetCollection 集合传递新工作表的页索引来引用它。
  3. 获取工作表引用。
  4. 对工作表进行操作。
  5. 调用 Workbook 类的 Save 方法保存新的带有工作表的Excel文件。
//For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-C
Aspose::Cells::Startup();
//Output directory path
U16String outDir(u"..\\Data\\02_OutputDirectory\\");
//Path of output excel file
U16String outputManageWorksheets = outDir + u"outputManageWorksheets.xlsx";
//Create workbook
Workbook workbook;
// Adding a new worksheet to the Workbook object
int i = workbook.GetWorksheets().Add();
// Obtaining the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.GetWorksheets().Get(i);
// Setting the name of the newly added worksheet
worksheet.SetName(u"My Worksheet");
// Save the Excel file.
workbook.Save(outputManageWorksheets);
std::cout <<"New worksheet added successfully with in a workbook!" << std::endl;
Aspose::Cells::Cleanup();

通过页索引访问工作表

以下示例代码展示了如何通过指定索引访问或获取任何工作表。

//For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-C
Aspose::Cells::Startup();
//Source directory path
U16String srcDir(u"..\\Data\\01_SourceDirectory\\");
//Path of input excel file
U16String sampleManageWorksheets = srcDir + u"sampleManageWorksheets.xlsx";
//Load the sample Excel file
Workbook workbook(sampleManageWorksheets);
//Accessing a worksheet using its index
Worksheet worksheet = workbook.GetWorksheets().Get(0);
//Access the cell by its name.
Cell cell = worksheet.GetCells().Get(u"F7");
//Print the value of cell F7
U16String val = cell.GetStringValue();
//Print the value on console.
std::cout << "Value of cell F7: " << val.ToUtf8() << std::endl;
Aspose::Cells::Cleanup();

通过页索引删除工作表

当已知工作表的名称时,通过名称来删除工作表是有效的。 如果不知道工作表的名称,可使用 RemoveAt 方法的重载版本,该方法将工作表的页索引传递给它而不是工作表的名称。

//For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-C
Aspose::Cells::Startup();
//Source directory path
U16String srcDir(u"..\\Data\\01_SourceDirectory\\");
//Output directory path
U16String outDir(u"..\\Data\\02_OutputDirectory\\");
//Path of input excel file
U16String sampleManageWorksheets = srcDir + u"sampleManageWorksheets.xlsx";
//Path of output excel file
U16String outputManageWorksheets = outDir + u"outputManageWorksheets.xlsx";
//Load the sample Excel file
Workbook workbook(sampleManageWorksheets);
//Removing a worksheet using its sheet index
workbook.GetWorksheets().RemoveAt(0);
//Save the Excel file.
workbook.Save(outputManageWorksheets);
Aspose::Cells::Cleanup();