简体   繁体   English

将一个现有 excel 文件中的特定列复制到 python 中的另一个文件

[英]Copying a specific column from one existing excel file to another file in python

I am successfully copying the whole columns from one existing excel file to another file in python, but cannot copy a specific column from an existing excel file and writing it into another.我成功地将整个列从一个现有的 excel 文件复制到 python 中的另一个文件,但无法从现有的 excel 文件复制特定列并将其写入另一个文件。

Here is my code这是我的代码

wb = load_workbook('Ambulance2Centroids_16622.xlsx')
wb2 = load_workbook('test.xlsx')

sheet1 = wb.get_sheet_by_name('Sheet1')
sheet2 = wb2.get_sheet_by_name('Details')

for i in range (1, 10):
    for j in range (1, sheet1.max_column+1):
        sheet2.cell(row=i, column=j).value = sheet1.cell(row=i, column=j).value
wb.save('Ambulance2Centroids_16622.xlsx')
wb2.save('test.xlsx')

在此处输入图像描述

Here, i am trying to get FROM_ID only.在这里,我试图只获取 FROM_ID。

A couple of things to note:有几点需要注意:
The get_sheet_by_name attribute is depreciated you should just use wb[<sheetname>] as shown below. get_sheet_by_name属性已被贬值,您应该只使用wb[<sheetname>] ,如下所示。
There is no need to save a workbook (wb) that you have not changed.无需保存未更改的工作簿 (wb)。 Since you are only reading data from 'Ambulance2Centroids_16622.xlsx' to copy to 'test.xlsx' there are no changes to that wb and no need to save it.由于您仅从“Ambulance2Centroids_16622.xlsx”读取数据以复制到“test.xlsx” ,因此该 wb 没有更改,也无需保存。
The example below shows how to find the column in the original wb, in this case 'FROM_ID' and then copy the column to the destination wb 'test.xlsx'.下面的示例显示了如何在原始 wb 中查找列,在本例中为“FROM_ID”,然后将该列复制到目标 wb“test.xlsx”。

from openpyxl import load_workbook

wb = load_workbook('Ambulance2Centroids_16622.xlsx')
wb2 = load_workbook('test.xlsx')

# Use wb[<sheetname>] to assign sheets to variable 
sheet1 = wb['Sheet1']
sheet2 = wb2['Details']

search_text = 'FROM_ID'

for header_row in sheet1[1]:  # sheet1[1] means iterate row 1, header row
    if header_row.value == search_text:
        # Use the column letter of the found column to iterate the originating column and copy the cell value
        for dest_row, orig_col_c in enumerate(sheet1[header_row.column_letter], 1):  
            # Copying the originating cell value to column A (1) in destination wb  
            sheet2.cell(row=dest_row, column=1).value = orig_col_c.value

# Save test.xlsx only
# wb.save('Ambulance2Centroids_16622.xlsx')
wb2.save('test.xlsx')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM