2016-08-21 193 views
2

該函數被多次調用。我保留一個計數,以便第一次呼叫時,創建一個工作簿。然後我使用pd.ExcelWrite()寫入該工作簿。下一次執行else:並打開相同的工作簿。它的第一張紙被選中,最後一行被找到。 DataFrame寫在該行上。 這是我的代碼:如何將數據框追加到現有的Excel表單中?

def WriteFile (df): 
    if count1 == 1: 
     workbook = xlsxwriter.Workbook('pandas_simple.xlsx') 
     writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter') 
     df.to_excel(writer, index=False) 
     workbook.close() 
    else: 
     book = open_workbook('pandas_simple.xlsx') 
     sheet_names = book.sheet_names() 
     sheet = book.sheet_by_name(sheet_names[0]) 
     row = sheet.nrows 
     writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter') 
     df.to_excel(writer, index=False, header=False, startrow = row) 

我得到這個異常:

Exception Exception: Exception('Exception caught in workbook destructor. Explicit close() 
may be required for workbook.',) in <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook 
object at 0x000000000A143860>> ignored Exception 

而且我pandas_simple.xlsx也是代碼執行後是空的。我究竟做錯了什麼?

+0

[如何寫入現有的excel文件而不覆蓋數據(使用熊貓)?](http://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file -without-overwrite-data-using-pandas) – Merlin

+0

這個異常很可能是由於不通過'close()'或Pandas'save()'調用XlsxWriter工作簿析構函數造成的。該錯誤消息試圖暗示這一點。它可能無法解決您的整體問題,但作爲第一步,您應該添加'close()'或'save()'來解決異常。 – jmcnamara

+0

此外,您不能使用XlsxWriter重寫或附加到文件,您只會得到一個新文件。 – jmcnamara

回答

2

感謝@ski。

請參考上同樣的問題他答

How to write to an existing excel file without overwriting data (using pandas)?

import pandas 
from openpyxl import load_workbook 

book = load_workbook('Masterfile.xlsx') 
writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl') 
writer.book = book 
writer.sheets = dict((ws.title, ws) for ws in book.worksheets) 

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2']) 

writer.save() 
+0

這種方法不起作用。我有一個數據幀,我需要在xlsx文件中寫入。這項工作正在循環中完成。 Dataframe被重新加載,現在需要被添加到同一個xlsx文件中。 – EL323

2

你能做到這樣:

df = pd.DataFrame(np.arange(1, 31), columns=['val']) 
fn = 'd:/temp/test.xlsx' 
count = 0 

writer = pd.ExcelWriter(fn) 

for chunk in np.split(df, 3): 
    chunk.to_excel(writer, index=False, header=(count==0), startrow=count+(count!=0)) 
    count += len(chunk) 

writer.save() 

結果:

enter image description here

相關問題