复制和移动工作表
有时,您确实需要一些具有共同格式和数据的工作表。例如,如果您在季度预算上工作,您可能希望创建一个包含具有相同列标题、行标题和公式的工作表的工作簿。有一种方法可以做到这一点:先创建一个工作表,然后进行复制。
Aspose.Cells支持在工作簿内或工作簿之间复制和移动工作表。工作表、数据、格式、表、矩阵、图表、图像和其他对象都会以最高精度复制。
使用Microsoft Excel移动或复制工作表
以下是在工作簿内或工作簿之间复制和移动工作表涉及的步骤。
- 打开要接收工作表的工作簿。
- 切换到包含您想要移动或复制的工作表的工作簿,然后选择这些工作表。
- 在编辑菜单上,单击移动或复制工作表。
- 在“接收工作簿”框中,单击要接收工作表的工作簿。
- 若要将所选工作表移动或复制到新工作簿,请单击新建。
- 在之前工作表框中,单击要将移动或复制的工作表插入到其前面的工作表。
- 若要复制工作表而不是移动它们,请选中创建副本复选框。
在工作簿内复制工作表
Aspose.Cells提供了一个重载的WorksheetCollection.addCopy()方法,用于复制现有工作表。该方法的一个版本以源工作表的索引作为参数。另一个版本以源工作表的名称作为参数。
以下示例显示了如何在工作簿内复制现有工作表。
source_directory = "Examples/SampleFiles/SourceDirectory/" | |
output_directory = "Examples/SampleFiles/OutputDirectory/" | |
workbook = Workbook(source_directory + "Book1.xlsx") | |
# Create a Worksheets object with reference to the sheets of the Workbook. | |
sheets = workbook.getWorksheets() | |
# Copy data to a new sheet from an existing sheet within the Workbook. | |
sheets.addCopy("Sheet1") | |
# Save the excel file. | |
workbook.save(output_directory + "CopyWithinWorkbook_out.xlsx") |
在工作簿之间复制工作表
Aspose.Cells提供了Worksheet.copy()方法,用于将工作表复制到其他工作簿。该方法以源工作表对象作为参数。
以下示例显示了如何将一个工作表从一个工作簿复制到另一个工作簿。
source_directory = "Examples/SampleFiles/SourceDirectory/" | |
output_directory = "Examples/SampleFiles/OutputDirectory/" | |
workbook0 = Workbook(source_directory + "Book1.xlsx") | |
# Create a Worksheets object with reference to the sheets of the Workbook. | |
workbook1 = Workbook() | |
# Copy the first sheet of the first book into second book. | |
workbook1.getWorksheets().get(0).copy(workbook0.getWorksheets().get(0)) | |
# Save the excel file. | |
workbook1.save(output_directory + "CopyWorksheetsBetweenWorkbooks_out.xlsx") |
在工作簿内部移动工作表
Aspose.Cells提供了Worksheet.moveTo()方法,用于将工作表移到同一电子表格中的另一个位置。
以下示例显示了如何将工作表移动到工作簿内的另一个位置。
source_directory = "Examples/SampleFiles/SourceDirectory/" | |
output_directory = "Examples/SampleFiles/OutputDirectory/" | |
workbook = Workbook(source_directory + "sampleCMultipleWorksheets.xlsx") | |
# Get the first worksheet in the book. | |
sheet = workbook.getWorksheets().get(0) | |
# Move the first sheet to the third position in the workbook. | |
sheet.moveTo(2) | |
# Save the excel file. | |
workbook.save(output_directory + "MoveWorksheet_out.xlsx") |