[英]How can I pull data by uniqueid from an xlsx file and write that data to another xlsx file with the same column name using Python?
我已經多次問過這個問題,但這次,我將同時使用 xlsx。 直到現在我還不知道如何正確地做到這一點,所以我再次尋求您的專業知識。 基本上,我想創建一個 Python 腳本來從 excel 文件中提取數據並寫入另一個 excel 文件。 例如:
兩者的初始值 Excel 文件:
XLSX1 XLSX2
Column_A Column_B Column_A Column_B
A A 21
B B 25
C C 2
D D 5
E E 9
F F 10
G G 15
H H 16
應用腳本后,XLSX2 的 Column_B 將寫入 XLSX1 的 Column_B:
XLSX1 XLSX2
Column_A Column_B Column_A Column_B
A 21 A 21
B 25 B 25
C 2 C 2
D 5 D 5
E 9 E 9
F 10 F 10
G 15 G 15
H 16 H 16
最初,用戶會選擇從 XLSX1 中選擇哪些行,並根據 uniqueid(Column_A) 從 XLSX2 中提取數據,我認為這很困難。 因此,如果我可以從 XLSX2 的 Column_B 復制整個數據並將其按 uniqueid(A、B、C、D、E、F、G、H)寫入 XLSX1 的 Column_B,我將不勝感激。
(代表問題作者發布答案以將其移動到答案空間) 。
以下是對我有用的代碼。
import openpyxl
daily_data = openpyxl.load_workbook('C:/XLSX1.xlsx')
master_data = openpyxl.load_workbook('C:/XLSX2.xlsx')
daily_sheet = daily_data['Sheet']
master_sheet = master_data['Sheet']
for i in daily_sheet.iter_rows():
A = i[0].value
row_number = i[0].row
for j in master_sheet.iter_rows():
if j[0].value == A:
daily_sheet.cell(row=row_number, column=3).value = j[1].value
print(j[1].value)
daily_data.save('C:/XLSX1.xlsx')
最后一個示例將搜索到的 ID 和查找數據附加到工作表,這意味着在 XLSX1 中的“最后使用”行之后寫入了兩個值,ID 和數據,假設您只需要用戶在工作表中輸入的 ID。
如果我們返回示例 XLSX1 工作表,其中存在 ID,在本例中為工作表中存在的 A、B、C、D、E、F、G 和 H,此示例將像以前一樣請求 ID,這次更新數據其中 ID 已存在於 XLSX1 的(A 列)中
該代碼在 XLSX2(A 列)中搜索每個輸入的 ID,如果找到則從 B 列獲取數據,然后在 XLSX1(A 列)中搜索 ID 並將數據輸入到 B 列。
在測試 output 中,我混淆了 XLSX1 中的 ID,以顯示 XLSX1 中的代碼搜索,以將數據添加到 ID 所在的位置。
在示例運行中,輸入了 ID“d、x、a、g”,
輸入ID得到:d,x,a,g
由於 d、a 和 g 在 XLSX2 中,這些 ID 的數據已在 XLSX1 中更新
查看代碼運行前后的圖像。
代碼更新工作表,這意味着如果再次運行代碼並輸入“b”ID,則 XLSX1 將具有原始運行在“d、a & g”和“b”上的數據。
import openpyxl
import pandas as pd
import warnings
warnings.filterwarnings('ignore') # setting ignore as a parameter
daily_data = 'C:/XLSX1.xlsx'
master_data = 'C:/XLSX2.xlsx'
worksheet = 'Sheet'
### Example sheet IDs A, B, C, D, E, F, G, H,
### Get IDs from the user (comma separated entry) and add to list ids_list
input_ids = input("Enter the IDs to obtain: ")
### Entered IDs are uppercased and stripped of white spaces.
ids_list = [item.strip().upper() for item in input_ids.split(',')]
### Load the Master sheet to Pandas for searching
df1 = pd.read_excel(master_data, sheet_name=worksheet)
### Load the Daily sheet to Pandas for searching
df2 = pd.read_excel(daily_data, sheet_name=worksheet)
### Column names for writing back to excel sheet
column_list = df2.columns
### Open writer for pandas dataframe (df) write back to excel
### mode a = append, overlay the existing sheet
writer = pd.ExcelWriter(daily_data,
mode='a',
if_sheet_exists='overlay',
engine='openpyxl')
for uid in ids_list:
### Search 1st col of XLSX2 df for the ID
search1 = df1.loc[df1.iloc[:,0] == uid]
### If search returns a value then add to the location
if search1.size > 0:
### Search 1st col of XLSX1 dataframe for the ID
search2 = df2.loc[df2.iloc[:,0] == uid]
### Update XLSX1 df with the data value from XLSX2 df
df2.at[search2.index[0], df2.iloc[:, 1].name] = df1.iloc[:,1].loc[search1.index[0].item()]
### Write updated dataframe to XLSX1 sheet
df2.to_excel(writer, sheet_name=worksheet, startrow=1, header=False, index=False)
### Drop pandas header formatting
book = writer.book
sheet = writer.sheets[worksheet]
for idx, val in enumerate(column_list,1):
sheet.cell(row=1, column=idx).value = val
### Save XLSX1 workbook
writer.save()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.