2017-07-16 36 views
0

我有一系列的10個熊貓數據框,每個有100行和6列。我正在嘗試使用openpyxl將數據寫入xlsx。每個數據框應位於工作簿的單獨工作表中。這些表格正在創建中,但是,所有結果都只輸入到第一張表格中(所以我得到10張紙張,9張空白紙張和一張1000行 - 當我應該有10張100行的紙張時)。我怎樣才能解決這個問題?OPENPYXL填充新的工作表

這裏是第2張代碼:

from openpyxl import Workbook 

# Create the hospital_ranking workbook 
hospital_ranking = Workbook() 
dest_filename1 = "hospital_ranking.xlsx" 

ws1 = hospital_ranking.active 
ws1.title = "Nationwide" 

from openpyxl.utils.dataframe import dataframe_to_rows 

# Write the nationwide query to ws1 
for r in dataframe_to_rows(national_results, index = False, header = True): 
    ws1.append(r) 

for cell in ws1['A'] + ws1[1]: 
    cell.style = 'Pandas' 

# Create the worksheet for each focus state 

# CA 
ws2 = hospital_ranking.create_sheet(title = 'California') 
ws2 = hospital_ranking.active 


# Write the CA query to ws2 
for r in dataframe_to_rows(ca_results, index = False, header = True): 
    ws2.append(r) 

for cell in ws2['A'] + ws2[1]: 
    cell.style = 'Pandas' 

hospital_ranking.save(filename = os.path.join("staging/") + dest_filename1) 

回答

2

您創建的表後,您需要參考吧: 不要重新綁定ws2到工作簿的活動工作表。

ws2 = hospital_ranking.active 

是一樣的:

ws2 = ws1 
+0

'代碼' WS2 = hospital_ranking.create_sheet(標題= '加州') WS2 = hospital_ranking.get_sheet_by_name( '加州') WS2 = hospital_ranking.active '代碼' 仍然產生相同的結果 – zsad512

+0

@ zsad512 - - 只是刪除'ws2 = hospital_ranking.active'它指向活動工作表(第一個) – PRMoureu

1

你是過分複雜的事情,並不需要大部分(如果不是全部)的代碼您發佈。只需使用df.to_excel即可接受sheet_name參數。

import pandas as pd 

ew = pd.ExcelWriter('excel.xlsx') 

list_of_dfs = [df1, df2, df3] 
list_of_worksheet_names = [sheet1, sheet2, sheet3] 
for df, sheet_name in zip(list_of_dfs, list_of_worksheet_names): 
    df.to_excel(ew, sheet_name=sheet_name) 

ew.save() 
+0

如何將生成的電子表格寫入「暫存」目錄? – zsad512

+0

以及如何忽略索引? – zsad512

+0

如果我能得到這兩個問題的答案,我會接受這個答案,因爲它們對我的任務是絕對必要的,並且長期完成這些任務。 – zsad512