简体   繁体   中英

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.):

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.

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.

How can this method be modified so that it first deletes the Data sheet before putting my DF in its place?

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.

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