当前位置: 首页 > 工具软件 > Excel Writer > 使用案例 >

Pandas Excel Writer writer.book = book的原因

姜晨
2023-12-01
工作:

from openpyxl import load_workbook
import pandas as pd
file = r'YOUR_PATH_TO_EXCEL_HERE'

df1 = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
book = load_workbook(file)
writer = pd.ExcelWriter(file, engine='openpyxl')
writer.book = book # <---------------------------- piece i do not understand
df1.to_excel(writer, sheet_name='New', index=None)
writer.save()

在ExcelWriter的源代码中,它初始化空工作簿并删除所有工作表,writer.book = book将原来表里面的内容保存到writer中

import numpy as np
import pandas as pd
import openpyxl
writer = pd.ExcelWriter('豆瓣副本.xlsx')
#print(type(writer))
df1 = pd.DataFrame({'V1':np.random.rand(100),'V2 ':np.random.rand(100),'V3':np.random.rand(100)})
book = openpyxl.load_workbook(writer.path)
#print(type(book))
writer.book = book #将豆瓣副本里面原来的表保存,否则原有表内容消失,只有新保存的df
df1.to_excel(writer,sheet_name='sheet2',index=False)
writer.save()
writer.close()
 类似资料: