杰瑞科技汇

Python如何复制工作表?

Of course! In Python, "copying a sheet" most commonly refers to working with spreadsheet files like Excel (.xlsx) or Google Sheets. The most popular and powerful library for this in Python is openpyxl.

I'll guide you through several common scenarios:

  1. Copying a Sheet within the Same Excel File (e.g., "Sheet1" -> "Sheet1_Copy")
  2. Copying a Sheet from One File to Another (e.g., copy data.xlsx to report.xlsx)
  3. Creating a New Sheet Based on an Existing One (with modifications)

Scenario 1: Copying a Sheet within the Same File

This is the most straightforward case. You load the workbook, copy a sheet by its name, and give the new sheet a unique name.

First, make sure you have openpyxl installed:

pip install openpyxl

Example Code:

Let's assume you have an Excel file named my_workbook.xlsx with a sheet named "Sales".

import openpyxl
from openpyxl.utils import get_column_letter
# --- 1. Load the existing workbook ---
try:
    workbook = openpyxl.load_workbook("my_workbook.xlsx")
except FileNotFoundError:
    print("Error: 'my_workbook.xlsx' not found.")
    exit()
# --- 2. Define the source and new sheet names ---
source_sheet_name = "Sales"
new_sheet_name = "Sales_Backup"
# --- 3. Check if the source sheet exists ---
if source_sheet_name not in workbook.sheetnames:
    print(f"Error: The sheet '{source_sheet_name}' does not exist in the workbook.")
else:
    # --- 4. Copy the source sheet ---
    # The copy is created *before* the source sheet
    source_sheet = workbook[source_sheet_name]
    new_sheet = workbook.copy_worksheet(source_sheet)
    # --- 5. Rename the new sheet ---
    new_sheet.title = new_sheet_name
    # Optional: Modify the new sheet (e.g., add a note)
    new_sheet["A1"] = "This is a backup copy."
    # --- 6. Save the workbook (this will overwrite the original file) ---
    # It's good practice to save with a new name to avoid accidental loss.
    workbook.save("my_workbook_copy.xlsx")
    print(f"Successfully copied '{source_sheet_name}' to '{new_sheet_name}' in 'my_workbook_copy.xlsx'.")

How it works:

  • openpyxl.load_workbook(): Opens an existing Excel file.
  • workbook.copy_worksheet(source_sheet): This is the key function. It creates an exact copy of the source_sheet and adds it to the workbook object. The new sheet is inserted before the original sheet.
  • new_sheet.title = ...: You must rename the new sheet, as its default title will be the same as the original (e.g., "Sales (2)").
  • workbook.save(): Saves the modified workbook. Important: This will overwrite the file if you use the same name. Always save to a new name unless you intend to modify the original.

Scenario 2: Copying a Sheet from One File to Another

This is slightly more complex. You need to load two workbooks: the source and the destination. You then copy the sheet from the source workbook to the destination workbook.

Example Code:

Let's say you have source_data.xlsx with a sheet named "Products" and you want to copy it into report_template.xlsx.

import openpyxl
# --- 1. Load both workbooks ---
try:
    source_workbook = openpyxl.load_workbook("source_data.xlsx")
    destination_workbook = openpyxl.load_workbook("report_template.xlsx")
except FileNotFoundError as e:
    print(f"Error: File not found - {e.filename}")
    exit()
# --- 2. Define sheet names ---
source_sheet_name = "Products"
new_sheet_name_in_dest = "Product_Data"
# --- 3. Check if the source sheet exists ---
if source_sheet_name not in source_workbook.sheetnames:
    print(f"Error: The sheet '{source_sheet_name}' does not exist in 'source_data.xlsx'.")
else:
    # --- 4. Copy the sheet from source to destination ---
    source_sheet = source_workbook[source_sheet_name]
    # The copy_worksheet method belongs to a workbook object
    new_sheet = destination_workbook.copy_worksheet(source_sheet)
    # --- 5. Rename the new sheet in the destination workbook ---
    new_sheet.title = new_sheet_name_in_dest
    # --- 6. Save the destination workbook ---
    destination_workbook.save("final_report.xlsx")
    print(f"Successfully copied '{source_sheet_name}' to '{new_sheet_name_in_dest}' in 'final_report.xlsx'.")

How it works:

  • We load both source_data.xlsx and report_template.xlsx.
  • We get the sheet from the source_workbook.
  • We call destination_workbook.copy_worksheet(), passing the sheet object from the other workbook. openpyxl handles the copying between the two workbook objects.
  • We rename the new sheet within the destination_workbook.
  • We save the destination_workbook with its new content.

Scenario 3: Creating a New Sheet Based on an Existing One (with Modifications)

Sometimes you don't want a perfect copy. You want a template. In this case, you can manually copy the data, cell by cell, and apply your own logic.

Example Code:

Let's copy the "Template" sheet but change a header and clear the data rows.

import openpyxl
# --- 1. Load the workbook ---
workbook = openpyxl.load_workbook("template_workbook.xlsx")
# --- 2. Get the source sheet ---
source_sheet_name = "Template"
if source_sheet_name not in workbook.sheetnames:
    print(f"Error: The sheet '{source_sheet_name}' does not exist.")
    exit()
source_sheet = workbook[source_sheet_name]
# --- 3. Create a new sheet manually ---
new_sheet_name = "New_Entry"
new_sheet = workbook.create_sheet(title=new_sheet_name)
# --- 4. Copy data with modifications ---
# Copy the header row (row 1)
for col_num, cell in enumerate(source_sheet[1], 1):
    new_sheet.cell(row=1, column=col_num, value=cell.value)
# Change the header in the new sheet
new_sheet["A1"] = "ID" # Let's say the original was "Product ID"
# Copy only the first 3 data rows from the source
for row_num in range(2, 5): # Assuming data starts on row 2
    for col_num, cell in enumerate(source_sheet[row_num], 1):
        new_sheet.cell(row=row_num, column=col_num, value=cell.value)
# Clear all other data rows in the new sheet
for row in new_sheet.iter_rows(min_row=5, max_row=new_sheet.max_row, max_col=new_sheet.max_column):
    for cell in row:
        cell.value = None
# Add a note
new_sheet["A5"] = "Fill in the data above."
# --- 5. Save the workbook ---
workbook.save("new_workbook_with_template.xlsx")
print(f"Successfully created '{new_sheet_name}' based on '{source_sheet_name}'.")

How it works:

  • workbook.create_sheet(): Creates a brand new, empty sheet.
  • source_sheet[1]: In openpyxl, this gets you the first row of cells as a tuple.
  • enumerate(..., 1): We loop through the cells and get their column number, starting from 1.
  • new_sheet.cell(): We create or access a cell in the new sheet and set its value.
  • iter_rows(): A powerful method to loop through a range of rows, which we use here to clear out unwanted data.

Alternative: Using Pandas

If your primary goal is to work with the data in a sheet (not formatting, charts, etc.), the Pandas library is an excellent alternative. It's less about "copying sheets" and more about "copying data frames".

First, install pandas and openpyxl (the engine for reading xlsx):

pip install pandas openpyxl

Example Code:

import pandas as pd
# --- 1. Read a specific sheet from an Excel file into a DataFrame ---
df_source = pd.read_excel("my_workbook.xlsx", sheet_name="Sales")
# --- 2. Perform data manipulations if needed ---
# For example, add a new column
df_source['Copied_Flag'] = True
# --- 3. Save the DataFrame to a new sheet in a (potentially new) Excel file ---
# We use ExcelWriter to control where the sheet goes
with pd.ExcelWriter("data_report_pandas.xlsx", engine='openpyxl') as writer:
    df_source.to_sheet(writer, sheet_name="Sales_Data", index=False)
    # You can even write multiple DataFrames to different sheets
    # df_other_data.to_sheet(writer, sheet_name="Summary", index=False)
print("Successfully copied data using Pandas and saved to 'data_report_pandas.xlsx'.")

Summary: Which Method to Use?

Scenario Best Tool Why?
Need an exact copy (including formatting, formulas, charts) openpyxl copy_worksheet() is designed for this and preserves all workbook elements.
Need to copy data only (for analysis, cleaning, reporting) Pandas It's faster for large datasets and has powerful data manipulation tools built-in.
Need a template (copy structure but modify content/data) openpyxl (manual loop) Gives you fine-grained control over which cells and data to copy and how to change them.
分享:
扫描分享到社交APP
上一篇
下一篇