[英]Python: overwriting an existing sheet in Excel file
I'm using a following method to re-write an Excel sheet containing the data source (keeping all the other sheets with pivots, charts, etc.):我正在使用以下方法重新编写包含数据源的 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)
The initial file is the data_source, where I swap the Data sheet with my DF (df_name) and change the file's name to target_file.初始文件是 data_source,我将数据表与我的 DF (df_name) 交换并将文件名更改为 target_file。
My problem is - the Data sheet in the Excel file doesn't "erase" itself before swapping, so if the table that had been before in the Data sheet contained more columns or rows than the DF I'm inserting in the sheet, the other rows just stay as they were, messing up the result.我的问题是 - Excel 文件中的数据表在交换之前不会“擦除”自身,所以如果数据表中之前的表包含的列或行多于我在表中插入的 DF,则其他行保持原样,弄乱了结果。
How can this method be modified so that it first deletes the Data sheet before putting my DF in its place?如何修改此方法,以便在将我的 DF 放在其位置之前首先删除数据表?
Thanks is advance!谢谢是提前!
Well, all that had to be done was to add one more line of code:好吧,所要做的就是再添加一行代码:
book.remove(book['Data'])
So it all looks like:所以这一切看起来像:
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)
Case closed.结案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.