简体   繁体   中英

Pandas To Excel write to an existing xlsx file

I am trying to write a dataframe to an existing Excel worksheet on one workbook. I have other worksheets in this excel workbook which should not be affected. The worksheet I am looking to overwrite is a tab called 'Data'. The code I have below:

    df= pd.read_sql(sql='EXEC [dbo].[spData]', con=engine)

    excel_file_path = "C:/Shared/Test.xlsx"

    book = load_workbook(excel_file_path)
    writer = ExcelWriter(excel_file_path, engine='openpyxl')
    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

    df.to_excel(writer, sheet_name='Data', index=False, header=[
        'A','B','C','D','E','F'])
    writer.save()

The code has been running for ages in debug mode with no errors but I am not sure if the above is correct in what I am expecting it to do. I can see the file says 0KB which so it has got rid of the other worksheets as the original file was 55,939kb. I was able to use ExcelWriter and engine 'openpyxl' to write to a workbook as a new sheet. But in the above code I want to replace the content of a worksheet with the data from my dataframe.

这工作添加了 mode='a'

   writer = ExcelWriter(excel_file_path, engine='openpyxl', mode='a')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM