将pandas数据框写入现有工作簿

时间:2016-04-06 10:00:23

标签: python excel pandas

我想将数据框保存到文件的第二张,但我不能这样做而且我不知道为什么。

yfile = openpyxl.load_workbook(new_file, data_only=True) 
ws = yfile.worksheets[0] 
sheet2 = yfile.create_sheet() 
ws2 = yfile.get_sheet_by_name("Sheet").title = "Analysis" 
writer = pd.ExcelWriter(yfile, engine='xlsxwriter') 
df3.to_excel(writer, sheet_name='Analysis') 
writer.save()
yfile.save(new_file)                                          

我创建了表格'分析'但是当我保存在其中时,我收到了以下回复:"属性错误:'工作簿'对象没有属性'写'"

我需要修改什么?

2 个答案:

答案 0 :(得分:4)

使用以下辅助函数:

def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                       truncate_sheet=False, 
                       **to_excel_kwargs):
    """
    Append a DataFrame [df] to existing Excel file [filename]
    into [sheet_name] Sheet.
    If [filename] doesn't exist, then this function will create it.

    Parameters:
      filename : File path or existing ExcelWriter
                 (Example: '/path/to/file.xlsx')
      df : dataframe to save to workbook
      sheet_name : Name of sheet which will contain DataFrame.
                   (default: 'Sheet1')
      startrow : upper left cell row to dump data frame.
                 Per default (startrow=None) calculate the last row
                 in the existing DF and write to the next row...
      truncate_sheet : truncate (remove and recreate) [sheet_name]
                       before writing DataFrame to Excel file
      to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`
                        [can be dictionary]

    Returns: None
    """
    from openpyxl import load_workbook

    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    writer = pd.ExcelWriter(filename, engine='openpyxl')

    try:
        # try to open an existing workbook
        writer.book = load_workbook(filename)

        # get the last row in the existing Excel sheet
        # if it was not specified explicitly
        if startrow is None and sheet_name in writer.book.sheetnames:
            startrow = writer.book[sheet_name].max_row

        # truncate sheet
        if truncate_sheet and sheet_name in writer.book.sheetnames:
            # index of [sheet_name] sheet
            idx = writer.book.sheetnames.index(sheet_name)
            # remove [sheet_name]
            writer.book.remove(writer.book.worksheets[idx])
            # create an empty sheet [sheet_name] using old index
            writer.book.create_sheet(sheet_name, idx)

        # copy existing sheets
        writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
    except FileNotFoundError:
        # file does not exist yet, we will create it
        pass

    if startrow is None:
        startrow = 0

    # write out the new sheet
    df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

    # save the workbook
    writer.save()

注意:适用于Pandas< 0.21.0,将sheet_name替换为sheetname

演示:

In [127]: df = pd.DataFrame(np.random.rand(5, 3), columns=list('abc'))

In [128]: df
Out[128]:
          a         b         c
0  0.597353  0.770586  0.671231
1  0.628605  0.161283  0.397493
2  0.476206  0.701582  0.476809
3  0.045590  0.302834  0.857033
4  0.414820  0.478016  0.563258

In [129]: df.to_excel(filename)

In [130]: append_df_to_excel(filename, df, sheet_name="Sheet2", startrow=1, startcol=1)

In [131]: append_df_to_excel(filename, df, sheet_name="Sheet3", index=False)

In [132]: append_df_to_excel(filename, df, sheet_name="Sheet1", startcol=2, index=False)

结果:

Sheet 1中:

enter image description here

Sheet 2中:

enter image description here

表Sheet 3:

enter image description here

使用以下版本测试PS:

  • python:3.6.4
  • pandas:0.22.0
  • openpyxl:2.4.10

答案 1 :(得分:0)

您可以使用以下方式。 它将数据帧逐行写入excel文件。

from openpyxl.utils.dataframe import dataframe_to_rows
filename = r'some_file.xlsx'
df = some_dataframe

wb = load_workbook(filename)
if 'sh2' in wb.sheetnames:#to check whether sheet you need already exists
    ws = wb['sh2']
else:
    ws = wb.active
for r in dataframe_to_rows(df, index=False, header=True):
    ws.append(r)
wb.save(filename)