如何使用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
- 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)
- Loop through each row in the source sheet
- For each row, copy values only from the mapped columns to the target sheet
- 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_namewith 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




