向excel表格的sheet頁面添加數據,覆蓋原數據,不改變原excel其他的sheet頁面

使用openyxl庫向excel表格的sheet頁面添加數據,覆蓋原數據,不改變原excel其他的sheet頁面

import pandas as pd
from openpyxl import load_workbook


def write_excel(date1, date2):
    book = load_workbook(r'C:\Users\86159\Desktop\test.xlsx')
    writer = pd.ExcelWriter(r'C:\Users\86159\Desktop\test.xlsx', engine='openpyxl')
    writer.book = book

    idx = book.sheetnames.index("集中作業處人員信息")
    book.remove(book.worksheets[idx]) #刪除原數據
    book.create_sheet("集中作業處人員信息", idx)

    idy = book.sheetnames.index("託管部門人員信息")
    book.remove(book.worksheets[idy]) #刪除原數據
    book.create_sheet("託管部門人員信息", idy)

    writer.sheets = dict((ws.title, ws) for ws in book.worksheets) #保存其他用不到的sheet頁面
    date1.to_excel(writer, "集中作業處人員信息", index=False) #保存數據
    date2.to_excel(writer, "託管部門人員信息", index=False)
    writer.save()
    writer.close()


#創建dateframe數據
a = np.random.randint(1, 6, (5, 3))
date1 = pd.DataFrame(a, columns=['A', 'B', 'C'])

a = np.random.randint(1, 3, (5, 3))
date2 = pd.DataFrame(a, columns=['A', 'B', 'C'])

write_excel(date1,date2) #調用函數

原來的excel數據:
在這裏插入圖片描述
處理後的excel數據:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章