【问题标题】:OPENPYXL populate new worksheetsOPENPYXL 填充新工作表
【发布时间】:2017-12-21 07:59:47
【问题描述】:

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

这是前两张纸的代码:

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)

【问题讨论】:

    标签: python pandas openpyxl


    【解决方案1】:

    对我们来说更简单的方法可能是 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()
    

    【讨论】:

      【解决方案2】:

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

      ws2 = hospital_ranking.active
      

      等同于:

      ws2 = ws1
      

      【讨论】:

      • 'code' ws2 = hospital_ranking.create_sheet(title = 'California') ws2 = hospital_ranking.get_sheet_by_name('California') ws2 = hospital_ranking.active 'code' 仍然产生相同的结果
      • @zsad512 -- 只需删除 ws2 = hospital_ranking.active 它指向的活动表(第一个)
      【解决方案3】:

      您将事情过于复杂,并且不需要您发布的大部分(如果不是全部)代码。只需使用接受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()
      

      【讨论】:

      • 如何将生成的电子表格写入“暂存”目录?
      • 我怎样才能忽略索引?
      • 如果我能回答这两个问题,我会接受这个作为答案,因为它们对我的任务绝对必要,而且要完成它们还有很长的路要走
      • 使用 openpyxl 的实用程序为用户提供了更多的控制权,尤其是在使用现有工作簿时。
      猜你喜欢
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      相关资源
      最近更新 更多