2017-02-14 46 views
0

我需要一些關於python的幫助。基本上我有2個文件(對於這個例子將是file1和file2)。 File1裏面有幾張,file2只是一張。所以在file2中的一些工作後,現在我有我需要的DataFrame。我需要將此DataFrame粘貼到file1中的一個特定工作表中。從xlsx複製到另一個xlsx中的特定工作表

File1 

    A  B  C  D   E   F   G 
<data> <data> <data> <data> <formula> <formula> <formula> 
<data> <data> <data> <data> <formula> <formula> <formula> 
<data> <data> <data> <data> <formula> <formula> <formula> 
<data> <data> <data> <data> <formula> <formula> <formula> 
<data> <data> <data> <data> <formula> <formula> <formula> 
<data> <data> <data> <data> <formula> <formula> <formula> 

File2 

    A   B   C   D   
<Newdata> <Newdata> <Newdata> <Newdata> 
<Newdata> <Newdata> <Newdata> <Newdata> 
<Newdata> <Newdata> <Newdata> <Newdata> 
<Newdata> <Newdata> <Newdata> <Newdata> 
<Newdata> <Newdata> <Newdata> <Newdata> 
<Newdata> <Newdata> <Newdata> <Newdata> 

So now i need to update the file one with the new Data. 

File1 

    A   B   C   D   E   F   G   
<Newdata> <Newdata> <Newdata> <Newdata> <formula> <formula> <formula> 
<Newdata> <Newdata> <Newdata> <Newdata> <formula> <formula> <formula> 
<Newdata> <Newdata> <Newdata> <Newdata> <formula> <formula> <formula> 
<Newdata> <Newdata> <Newdata> <Newdata> <formula> <formula> <formula> 
<Newdata> <Newdata> <Newdata> <Newdata> <formula> <formula> <formula> 
<Newdata> <Newdata> <Newdata> <Newdata> <formula> <formula> <formula> 

所以列E,F和G有一些公式,通過數據的列A,B,C更新,D.

我嘗試不同的選項來做到這一點。連接兩個文件並顯示我嘗試的列,加載這兩個文件並創建一個包含新信息的新文件...主要問題是在file1中我有幾張紙,需要保留,因爲列E,F和G(具有公式的那個)將更新其他工作表。

所以,如果有人給我這個請一個手。謝謝,我會感激幫助

+0

使用'openpyxl'。它將能夠處理'.xlsx'文件中需要的所有內容。如果對這兩個文件使用'xlsx',請告訴我,我會盡我所能幫助您。 只注意到它的'xlsb'文件。不知道這些:( – Sid

+0

@Sid .xlsb是一個大的xlsx,我可以在這兩個文件中使用xlsx,你能幫我嗎 –

+0

嗯..我似乎無法保持行E,F和G行數據。試圖找出原因,如果你想我可以將代碼發佈到現在。 – Sid

回答

0

有毫無疑問是一個更好的方式來做到這一點,但是這是我能做到這一點:

from openpyxl import load_workbook 
import os 

os.chdir("Directory Path here") 
wb = load_workbook('file.xlsx') 
ws = wb.active 
#or use the below to pick sheet as by name 
# ws = wb.get_sheet_by_name 
inde = [] 
val = [] 
for col in ws.iter_cols(): 
    for cell in col: 
     h = cell.coordinate 
     inde.append(h) 
     v = cell.value 
     val.append(v) 
diction = dict(zip(inde,val)) 

wb1=load_workbook('file1.xlsx') 
ws1 = wb1.active 

for i in diction.keys(): 
    ws1[i] = diction[i] 
    wb1.save('file1.xlsx') 
+0

謝謝Sid,讓我試試這個解決方案。 –

+0

@CarlosArronteBello做到了嗎? – Sid

+0

嗨,早上好,很抱歉,很久沒有回答。不是工作,我收到這個錯誤。 '在col中ws.iter_cols(): AttributeError:'Worksheet'對象沒有屬性'iter_cols'' –

相關問題