我正在使用熊猫更新现有的Excel工作簿。使用ExcelWriter
对象时,是否可以覆盖工作表(如果存在),否则可以创建新工作表?我已经添加了新工作表的代码,但是当我尝试覆盖现有工作表时,它会添加一个名称稍有不同的新工作表(例如:如果工作表'data1'存在,则运行代码会添加一个新工作表,命名为'data1 1')
import pandas as pd
import openpyxl
path = 'test-out.xlsx'
book = openpyxl.load_workbook(path)
df1 = pd.DataFrame({'a': range(10), 'b': range(10)})
writer = pd.ExcelWriter(path, mode='a')
writer.book = book
df1.to_excel(writer, sheet_name='data1')
writer.save()
答案 0 :(得分:3)
使用writer
将工作表传递到writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
:
import pandas as pd
import openpyxl
path = 'test-out.xlsx'
book = openpyxl.load_workbook(path)
df1 = pd.DataFrame({'a': range(10), 'b': range(10)})
writer = pd.ExcelWriter(path, mode='a')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df1.to_excel(writer, sheet_name='data1')
writer.save()
编辑:
似乎您甚至不需要mode='w'
,writer = pd.ExcelWriter(path, mode='a')
仍在工作...