[英]Writing dataframe to excel sheet with openpyxl
I am trying to write a dataframe that I have to an excel sheet. 我正在尝试将必须具有的数据框写入Excel工作表。 This is something that I have done many times in several ways and I can't figure out where my error is right now.
这是我以几种方式做了很多次的事情,现在我无法弄清楚我的错误在哪里。
Pandas 23.4 熊猫23.4
My code: 我的代码:
#initialize stuff
book = load_workbook(os.path.commonpath(output))
writer = pd.ExcelWriter(os.path.commonpath(output), engine = 'openpyxl')
writer.book = book
#Check for sheet in my excel book, if not there create it
if not 'CHECK' in book.sheetnames:
book.create_sheet('CHECK')
#Remove default excel sheets if present, and save changes to sheet
try:
book.remove_sheet(book['Sheet1'])
except:
pass
book.save(os.path.commonpath(output))
#THIS LINE WAS MISSING, CAUSING THE ERROR!
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
#write it all out at the first blank row in the excel sheet
df.to_excel(writer, sheet_name = 'CHECK', startrow = writer.sheets['CHECK'].max_row, index=False)
For whatever reason I get the following error: KeyError: 'CHECK'
无论出于何种原因,我都会收到以下错误:
KeyError: 'CHECK'
I have been scratching my head over this because I've used almost this exact code before and it worked well. 我一直在为此抓狂,因为我之前几乎使用了这段确切的代码,而且效果很好。
You should change 你应该改变
df.to_excel(writer, sheet_name = 'CHECK', startrow = writer.sheets['CHECK'].max_row, index=False)
df.to_excel(writer,sheet_name ='CHECK',startrow = writer.sheets ['CHECK']。max_row,index = False)
To: 至:
df.to_excel(output, sheet_name = 'CHECK', startrow = book['CHECK'].max_row, index=False)
Just before df.to_excel(output, sheet_name = 'CHECK', startrow = book['CHECK'].max_row, index=False)
a critical line is missing on my end!! 就在
df.to_excel(output, sheet_name = 'CHECK', startrow = book['CHECK'].max_row, index=False)
,我的末端缺少关键行!
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
^ is the perpetrator that was missing, original question will be updated. ^是所遗失的肇事者,原始问题将被更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.