[英]Pandas To Excel write to an existing xlsx file
I am trying to write a dataframe to an existing Excel worksheet on one workbook.我正在尝试将数据框写入一个工作簿上的现有 Excel 工作表。 I have other worksheets in this excel workbook which should not be affected.
我在这个 excel 工作簿中还有其他不应受到影响的工作表。 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.
我可以看到文件显示为 0KB,因此它已经删除了其他工作表,因为原始文件为 55,939kb。 I was able to use ExcelWriter and engine 'openpyxl' to write to a workbook as a new sheet.
我能够使用 ExcelWriter 和引擎“openpyxl”将工作簿作为新工作表写入。 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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.