OPENPYXL填充新工作表

时间:2017-07-16 20:36:21

标签: python pandas openpyxl

我有一系列10个pandas数据帧,每个数据帧有100行和6列。我正在尝试使用openpyxl将数据写入xlsx。每个数据框应位于工作簿的单独工作表中。正在创建工作表,但是,所有结果仅在第一张纸上输入(因此我得到10张纸,9张空,一张1000行 - 当我应该有10张纸,每张100行)。我怎样才能解决这个问题?

以下是前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)

3 个答案:

答案 0 :(得分:2)

创建工作表后,您需要引用它: 不要将ws2重新绑定到工作簿的活动表。

ws2 = hospital_ranking.active

与:

相同
ws2 = ws1

答案 1 :(得分:2)

您过于复杂,并且不需要您发布的大部分(如果不是全部)代码。只需使用接受sheet_name参数的df.to_excel即可。

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()

答案 2 :(得分:2)

更简单的方法可能是我们df.to_excel

# Create a Pandas Excel writer using openpyxl as the engine.
writer = pd.ExcelWriter(xlfile, engine='openpyxl')

# Write each dataframe to a different worksheet.
df1.to_excel(writer, sheet_name='California')
df2.to_excel(writer, sheet_name='Arizona')
df3.to_excel(writer, sheet_name='Texas')

# Close the Pandas Excel writer and output the Excel file.
writer.save()