我正在尝试将必须具有的数据框写入Excel工作表。这是我以几种方式做了很多次的事情,现在我无法弄清楚我的错误在哪里。
熊猫23.4
我的代码:
#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)
无论出于何种原因,我都会遇到以下错误:KeyError: 'CHECK'
我一直在努力解决这个问题,因为我之前几乎使用了这段确切的代码,而且效果很好。
答案 0 :(得分:1)
您应该更改
df.to_excel(writer,sheet_name ='CHECK',startrow = writer.sheets ['CHECK']。max_row,index = False)
收件人:
df.to_excel(output, sheet_name = 'CHECK', startrow = book['CHECK'].max_row, index=False)
答案 1 :(得分:0)
在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)
^是失踪的肇事者,原始问题将得到更新。