1 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個(gè)贊
要將數(shù)據(jù)框保存到現(xiàn)有工作表,您必須在 Excel 編寫器中設(shè)置工作表集合。
試試這個(gè)代碼:
###### create test file ######
from openpyxl import load_workbook, Workbook
wb = Workbook()
ws = wb.active
ws.title='Monthly Premium' # rename default sheet
ws = wb.create_sheet('Monthly Losses') # add sheet
wb.save(r'Template1.xlsx')
######### main script #########
import pandas as pd
from openpyxl import load_workbook
#sample df
df = pd.DataFrame()
df["A"] = [1,2,3,4,5]
df["B"] = ["A", "B", "C", "D", "E"]
#print(df)
path = r'Template1.xlsx'
book = load_workbook(path)
writer = pd.ExcelWriter(path, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets) # prevent new sheet
df.to_excel(writer, sheet_name='Monthly Premium')
writer.save()
writer.close()
輸出
添加回答
舉報(bào)