[英]Python: overwriting an existing sheet in Excel file
我正在使用以下方法重新编写包含数据源的 Excel 工作表(将所有其他工作表与数据透视表、图表等一起保留):
from openpyxl import load_workbook
def excel_rewriter(data_source, df_name, target_file):
book = load_workbook(data_source)
writer = pd.ExcelWriter(data_source, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df_name.to_excel(writer, 'Data', index=False)
writer.save()
os.rename(data_source, target_file)
初始文件是 data_source,我将数据表与我的 DF (df_name) 交换并将文件名更改为 target_file。
我的问题是 - Excel 文件中的数据表在交换之前不会“擦除”自身,所以如果数据表中之前的表包含的列或行多于我在表中插入的 DF,则其他行保持原样,弄乱了结果。
如何修改此方法,以便在将我的 DF 放在其位置之前首先删除数据表?
谢谢是提前!
好吧,所要做的就是再添加一行代码:
book.remove(book['Data'])
所以这一切看起来像:
def excel_rewriter(data_source, df_name, target_file):
book = load_workbook(data_source)
book.remove(book['Data'])
writer = pd.ExcelWriter(data_source, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df_name.to_excel(writer, 'Data', index=False)
writer.save()
os.rename(data_source, target_file)
结案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.