![](/img/trans.png)
[英]Copying the segment from one Excel file to another with python: xlrd and xlsxwriter
[英]Copying a specific column from one existing excel file to another file in python
我成功地將整個列從一個現有的 excel 文件復制到 python 中的另一個文件,但無法從現有的 excel 文件復制特定列並將其寫入另一個文件。
這是我的代碼
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')
在這里,我試圖只獲取 FROM_ID。
有幾點需要注意:
get_sheet_by_name屬性已被貶值,您應該只使用wb[<sheetname>] ,如下所示。
無需保存未更改的工作簿 (wb)。 由於您僅從“Ambulance2Centroids_16622.xlsx”讀取數據以復制到“test.xlsx” ,因此該 wb 沒有更改,也無需保存。
下面的示例顯示了如何在原始 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.