2017-07-15 157 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实际上并没有调用工作表。