1 回答
TA贡献1784条经验 获得超7个赞
要将数据框保存到现有工作表,您必须在 Excel 编写器中设置工作表集合。
试试这个代码:
###### 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()
输出
添加回答
举报