![](/img/trans.png)
[英]How to create an Excel file extension .xlsx from a dictionary using openpyxl?
[英]Taking data from a dictionary and putting it into an Excel file using openpyxl
我正在使用 Reddit PRAW 模塊將 subreddit 的各種屬性保存到字典中,字典的格式是 {PostTitle: [id, author, upvotes]}
如果我想將字典的內容添加到一個 excel 文件中,每列對應於字典的屬性(A1 = PostTitle B1 = id 等等),我將如何在 openpyxl 中執行此操作?
由於 openpyxl 與列表配合得很好,您的問題可以簡化為如何將列表字典轉換為列表列表,此處已回答: Converting Python Dictionary to List of lists
執行您所要求的代碼:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = 'Posts'
# {PostTitle: [id, author, upvotes]}
data = {
'Working with Excel1': [
'111',
'aaa',
'1'
],
'Working with Excel2': [
'222',
'bbb',
'2'
],
'Working with Excel3': [
'333',
'ccc',
'3'
],
}
for record in [[k]+v for k,v in data.items()]:
ws.append(record)
wb.save('Reddit.xlsx')
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.