【问题标题】:Copy pandas dataframe to excel using openpyxl使用openpyxl将熊猫数据框复制到excel
【发布时间】:2016-08-08 00:36:17
【问题描述】:

我在模板文件中保存了一些复杂的格式,我需要将 Pandas 数据框中的数据保存到该文件中。问题是当我使用 pd.to_excel 保存到此工作表时,pandas 会覆盖格式。有没有办法以某种方式将 df 的值“粘贴”到工作表中?我正在使用熊猫 0.17

import openpyxl
import pandas as pd
wb= openpyxl.load_workbook('H:/template.xlsx')
sheet = wb.get_sheet_by_name('spam')
sheet.title = 'df data'
wb.save('H:/df_out.xlsx')

xlr = pd.ExcelWriter('df_out.xlsx')
df.to_excel(xlr, 'df data')
xlr.save()

【问题讨论】:

    标签: python pandas dataframe clipboard openpyxl


    【解决方案1】:

    我稍微修改了@CharlieClark 的最佳答案以避免索引(原始 Excel 文件中不存在该索引)。这是一个可以运行的代码:

    import pandas as pd
    from openpyxl.utils.dataframe import dataframe_to_rows
    from openpyxl import load_workbook
    wb = load_workbook('test.xlsx')  # load as openpyxl workbook; useful to keep the original layout
                                     # which is discarded in the following dataframe
    df = pd.read_excel('test.xlsx')  # load as dataframe (modifications will be easier with pandas API!)
    ws = wb.active
    df.iloc[1, 1] = 'hello world'    # modify a few things
    rows = dataframe_to_rows(df, index=False)
    for r_idx, row in enumerate(rows, 1):
        for c_idx, value in enumerate(row, 1):
            ws.cell(row=r_idx, column=c_idx, value=value)
    wb.save('test2.xlsx')
    

    【讨论】:

      【解决方案2】:

      openpyxl 2.4 带有一个实用程序,用于将 Pandas 数据帧转换为 openpyxl 可以直接使用的东西。代码看起来有点像这样:

      from openpyxl.utils.dataframe import dataframe_to_rows
      rows = dataframe_to_rows(df)
      
      for r_idx, row in enumerate(rows, 1):
          for c_idx, value in enumerate(row, 1):
               ws.cell(row=r_idx, column=c_idx, value=value)
      

      您可以调整枚举的开始以将单元格放置在您需要的位置。

      更多信息请参见openpyxl documentation

      【讨论】:

      • 我们应该有一个像DataFrame这样的功能来工作吗?
      • @Abbas 我认为这根本没有必要。一旦 2.4 发布,我将与 Pandas 一起在 df.to_excel() 方法中使用它。
      • 这是否允许我从 df 选择不同的行到文件中的任意行并为所有行重复它?
      • 这是关于如何使用 pandas 和 openpyxl 覆盖现有工作表数据的长期失传的答案!我补充说: rows = dataframe_to_rows(df, index=False, header=True)
      【解决方案3】:

      这里是你使用clipboard的解决方案:

      import openpyxl
      import pandas as pd
      import clipboard as clp
      
      #Copy dataframe to clipboard
      df.to_clipboard()
      #paste the clipboard to a valirable
      cells = clp.paste()
      #split text in varialble as rows and columns
      cells = [x.split() for x in cells.split('\n')]
      
      #Open the work book
      wb= openpyxl.load_workbook('H:/template.xlsx')
      #Get the Sheet
      sheet = wb.get_sheet_by_name('spam')
      sheet.title = 'df data'
      #Paste clipboard values to the sheet
      for i, r in zip(range(1,len(cells)), cells):
          for j, c in zip(range(1,len(r)), r):
              sheet.cell(row = i, column = j).value = c
      #Save the workbook
      wb.save('H:/df_out.xlsx')
      

      【讨论】:

      • 这会创建两个中间数据结构:剪贴板和单元格。
      • 我在openpyxl中寻找类似粘贴剪贴板的东西,类似于pandas中的功能。
      • 会有ws.values 属性,我们可以通过该属性轻松获取工作表的值,但这不是可写的。 ws.iter_cols() 将为可编辑的工作表提供一个列式界面。
      猜你喜欢
      • 2018-05-24
      • 2015-06-10
      • 2020-12-14
      • 2016-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-05
      • 2021-09-24
      相关资源
      最近更新 更多