2017-07-15 63 views
-2

我有一個在openpyxl中創建的工作簿,並且正在嘗試使用查詢中的df填充工作表。但是,當我打開xlsx時,工作表已創建,但所有查詢都連接到第一個工作表,其他工作表都是空白的。哪裏不對?OPENPYXL:寫入新的工作表

下面是代碼:

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' 

hospital_ranking.save(filename = staging_dir + dest_filename1) 

# 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 = staging_dir + dest_filename1) 
+0

*電子表格中的信息錯誤* ...出了什麼問題?列混合了嗎?行刪除?完全不同的數據?缺失數據?你的代碼看起來是創建空狀態命名錶,但沒有數據。 – Parfait

+1

你不想索引,但你故意將它們設置爲「真」。也許你應該在複製和粘貼代碼時多閱讀一下代碼。 –

+0

@Parfait - 電子表格中填充了電子表格中完全不同的數據,電子表格加載到程序的更高版本 – zsad512

回答

1

第一:

如果要刪除 '索引',而寫入Excel工作表,使用

index=False 

,而不是

index=True 

在您的代碼中。

第二個: 您已經提到過要將每個數據框保存到新的工作表中。但是,我沒有看到你在你的代碼中這樣做。

您正在創建的工作表,命名爲「加利福尼亞」,「佛羅里達」等等,但我似乎並沒有在任何地方你的腳本你填充它們喜歡你的工作做WS1,即

for r in dataframe_to_rows(df, index=False, header=True): 
    ws2.append(r); 

其次,

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

最終被

wb.save(filename=dest_filename); 

保存要做到這一點,你可以將事件根據你如何從查詢中創建你的熊貓數據框,完全循環整個過程。

爲了您的調試: 請確保您的查詢返回您想要的並正確存儲在熊貓數據框中。也許你可以在寫作之前中級評估熊貓數據框。

你是什麼意思,「工作表中沒有正確的信息?」你能詳細解釋一下嗎?

保存到特定的目錄:

targetDir = "<Absolute path to your target directory>" 

wb.save(filename=targetDir+dest_filename); 

Forexample:

targetDir="/home/rb/staging" 

WB。保存(文件名= TARGETDIR + dest_filename);

wb.save(filename=os.path.join("staging/")+dest_filename); 

(使用字符串連接)

+0

@RusselB中,查詢運行良好,數據框正確填充。我還沒有添加代碼來填充工作簿中的其他工作表,因爲第一個工作表沒有正確填充。一旦我得到第一張工作表 - 我將複製並修改代碼以用適當的數據框填充其他工作表 – zsad512

+0

如何保存到特定的目錄? – zsad512

+0

請看我更新的答案。 – RussellB

0

添加作爲另一種答案,因爲這個問題已經改變和解決方案的可讀性,

from openpyxl import Workbook 
import pandas as pd 
from openpyxl.utils.dataframe import dataframe_to_rows 
import numpy as np 
import os 

wb = Workbook(); 
dest_filename='myWorkbook.xlsx'; 

## City names - array 
cityNames = ['Nation wide','California', 'Florida', 'Georgia', 'Michigan']; 

# Creating dicitonary of dataframes 
dfDict = {}; 

for i in range(len(cityNames)): 
newData = np.random.randn(3,3); #Substitute at this point your dataframe building query from a list of query strings may be 
dfDict[i] = pd.DataFrame(newData); # Or you can do it inline @ this point 


def writeSheets(cityList): 
    for n in range(len(dfDict)): 
     ws = wb.create_sheet(title=cityList[n], index=n); 
     for r in dataframe_to_rows(dfDict[n], index=False, header=True): 
      ws.append(r); 

     for cell in ws['A']+ws[1]: 
      cell.style = "Pandas"; 
    wb.save(filename=os.path.join("/home/russellb/russell/Python/"+dest_filename)); 

writeSheets(cityNames); 
+0

我已經有數據框,但我不知道如何將每個查詢添加到字典。此外,您在def writeSheets(citylist)中使用的語法與我已經使用的語法完全相同 - 所以我不知道如何將這些工作表添加到工作簿中(或者在這種情況下) – zsad512

+0

如果您已經有了它們,創建一個列表並循環它們,如上所示。至於表單,我沒有設置活動表單。可能你可以檢查它的作用以獲得理解。是否試過運行我的腳本? – RussellB

1

與不是新的工作表的問題造成了以下錯誤:

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

對於每張紙。這不起作用,我將代碼更改爲:

ws2 = hospital_ranking.create_sheet(title = 'California') 
ws2 = hospital_ranking.get_sheet_by_name('California') 

並且所有工作表均正確填充。問題是wb.active實際上並沒有調用工作表。