簡體   English   中英

Python:覆蓋 Excel 文件中的現有工作表

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM