You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用Openpyxl将一个工作簿中的指定列复制到另一个工作簿

Hey there! I see you're already comfortable copying entire sheets or single columns with openpyxl, and now you need to copy specific columns across workbooks — let's get this sorted for you.

Solution for Copying Specific Columns Between Excel Workbooks

Your current code copies every cell from the source sheet to the target, but we can tweak it to focus only on the columns you need. The key is to create a column mapping that links the source columns (A, D, G) to their target positions (A, B, C) in the second workbook.

Step-by-Step Breakdown

  1. Define which source columns correspond to which target columns (remember openpyxl uses 1-based indexing: A=1, D=4, G=7; target A=1, B=2, C=3)
  2. Loop through each row in the source sheet
  3. For each row, copy values only from the mapped columns to the target sheet
  4. Save the updated target workbook

Modified Code

from openpyxl import load_workbook

# Load both source and target workbooks
wb_source = load_workbook('test1.xlsx')
wb_target = load_workbook('test2.xlsx')

# Access the specific sheets we need (note: get_sheet_by_name is deprecated now!)
ws_source = wb_source['Sheet1']
ws_target = wb_target['Sheet1']

# Create a mapping: (source_column_number, target_column_number)
column_mapping = [
    (1, 1),   # Source column A → Target column A
    (4, 2),   # Source column D → Target column B
    (7, 3)    # Source column G → Target column C
]

# Get the total number of rows we need to copy from the source sheet
max_rows = ws_source.max_row

# Loop through each row and copy values for our mapped columns
for row_num in range(1, max_rows + 1):
    for source_col, target_col in column_mapping:
        # Grab the value from the source cell
        source_value = ws_source.cell(row=row_num, column=source_col).value
        # Assign that value to the corresponding target cell
        ws_target.cell(row=row_num, column=target_col).value = source_value

# Save the changes to the target workbook
wb_target.save('test2.xlsx')

Important Notes

  • Deprecation Heads-Up: I swapped out get_sheet_by_name with bracket notation (wb['Sheet1']) because the former is no longer recommended in newer openpyxl versions — the bracket syntax is the current standard.
  • Efficiency: This approach only processes the columns you care about, which is faster than copying the entire sheet if your source has lots of unused columns.
  • Overwrite Warning: Double-check that you don't have critical data in the target sheet's A, B, or C columns, as this code will overwrite those values!

内容的提问来源于stack exchange,提问作者Jpjoshuapeter

火山引擎 最新活动