簡體   English   中英

使用 openpyxl 從字典中獲取數據並將其放入 Excel 文件中

[英]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.

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