append dataframe to excel with pandas

前端 未结 4 460
刺人心
刺人心 2020-11-27 07:13

I desire to append dataframe to excel

This code works nearly as desire. Though it does not append each time. I run it and it puts data-frame in excel. But each ti

相关标签:
4条回答
  • 2020-11-27 07:38

    Here is a helper function:

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

    Usage examples:

    filename = r'C:\OCC.xlsx'
    
    append_df_to_excel(filename, df)
    
    append_df_to_excel(filename, df, header=None, index=False)
    
    append_df_to_excel(filename, df, sheet_name='Sheet2', index=False)
    
    append_df_to_excel(filename, df, sheet_name='Sheet2', index=False, startrow=25)
    
    0 讨论(0)
  • 2020-11-27 07:39

    I tried to read an excel, put it in a dataframe and then concat the dataframe from excel with the desired dataframe. It worked for me.

    def append_df_to_excel(df, excel_path):
        df_excel = pd.read_excel(excel_path)
        result = pd.concat([df_excel, df], ignore_index=True)
        result.to_excel(excel_path, index=False)
    
    df = pd.DataFrame({"a":[11,22,33], "b":[55,66,77]})
    append_df_to_excel(df, r"<path_to_dir>\<out_name>.xlsx")
    
    0 讨论(0)
  • 2020-11-27 07:44

    All examples here are quite complicated. In the documentation, it is much easier:

    def append_to_excel(fpath, df, sheet_name):
        with pd.ExcelWriter(fpath, mode="a") as f:
            df.to_excel(f, sheet_name=sheet_name)
    
    append_to_excel(<your_excel_path>, <new_df>, <new_sheet_name>)
    
    0 讨论(0)
  • 2020-11-27 07:51

    first of all, this post is the first piece of the solution, where you should specify startrow=: Append existing excel sheet with new dataframe using python pandas

    you might also consider header=False. so it should look like:

    df1.to_excel(writer, startrow = 2,index = False, Header = False)
    

    if you want it to automatically get to the end of the sheet and append your df then use:

    startrow = writer.sheets['Sheet1'].max_row
    

    and if you want it to go over all of the sheets in the workbook:

    for sheetname in writer.sheets:
        df1.to_excel(writer,sheet_name=sheetname, startrow=writer.sheets[sheetname].max_row, index = False,header= False)
    

    btw: for the writer.sheets you could use dictionary comprehension (I think it's more clean, but that's up to you, it produces the same output):

    writer.sheets = {ws.title: ws for ws in book.worksheets}
    

    so full code will be:

    import pandas
    from openpyxl import load_workbook
    
    book = load_workbook('test.xlsx')
    writer = pandas.ExcelWriter('test.xlsx', engine='openpyxl')
    writer.book = book
    writer.sheets = {ws.title: ws for ws in book.worksheets}
    
    for sheetname in writer.sheets:
        df1.to_excel(writer,sheet_name=sheetname, startrow=writer.sheets[sheetname].max_row, index = False,header= False)
    
    writer.save()
    
    0 讨论(0)
提交回复
热议问题