簡體   English   中英

使用openpyxl將數據框寫入Excel工作表

[英]Writing dataframe to excel sheet with openpyxl

我正在嘗試將必須具有的數據框寫入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'

我一直在為此抓狂,因為我之前幾乎使用了這段確切的代碼,而且效果很好。

你應該改變

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)

就在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)

^是所遺失的肇事者,原始問題將被更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM