Overwrite sheets in Excel with Python

后端 未结 1 1053
迷失自我
迷失自我 2021-01-14 21:03

I\'m new to Python (and programming in general) and am running into a problem when writing data out to sheets in Excel.

I\'m reading in an Excel file, performing a

相关标签:
1条回答
  • 2021-01-14 21:33

    From the pd.DataFrame.to_excel documentation:

    Multiple sheets may be written to by specifying unique sheet_name. With all data written to the file it is necessary to save the changes. Note that creating an ExcelWriter object with a file name that already exists will result in the contents of the existing file being erased.

    Try writing to the book like

    import pandas as pd
    df = pd.DataFrame({'col1':[1,2,3],'col2':[4,5,6]})
    writer = pd.ExcelWriter('g.xlsx')
    df.to_excel(writer, sheet_name = 'first_df')
    df.to_excel(writer, sheet_name = 'second_df')
    writer.save()
    

    If you inspect the workbook, you will have two worksheets.

    Then lets say you wanted to write new data to the same workbook:

    writer = pd.ExcelWriter('g.xlsx')
    df.to_excel(writer, sheet_name = 'new_df')
    writer.save()
    

    If you inspect the workbook now, you will just have one worksheet named new_df

    If there are other worksheets in the excel file that you want to keep and just overwrite the desired worksheets, you would need to use load_workbook.

    Before you wrtie any data, you could delete the sheets you want to write to with:

    std=book.get_sheet_by_name(<sheee_name>)
    book.remove_sheet(std)
    

    That will stop the behavior where a number gets appended to the worksheet name once you attempt to write a workbook with a duplicate sheet name.

    0 讨论(0)
提交回复
热议问题