简体   繁体   English

如何使用 openpyxl 从字典创建 Excel 文件扩展名 .xlsx?

[英]How to create an Excel file extension .xlsx from a dictionary using openpyxl?

I am new to the library import openpyxl using python and i went through many posts on stackoverflow to find a good example of the case below that i can learn from.我是使用python import openpyxl库的新手,我浏览了许多关于 stackoverflow 的帖子,以找到一个很好的案例示例,我可以从中学习。

I have the dictionary below.我有下面的字典。

dictionary字典

people = [
    {
        "Name": 'Adam',
        "Age": 28,
        "Country": "US",
    },
    {
        "Name": 'Helena',
        "Age": 18,
        "Country": "France",
    },
    {
        "Name": 'John',
        "Age": 23,
        "Country": "US",
    },
    {
        "Name": 'Remy',
        "Age": 34,
        "Country": "France",
    },
]

How can i possibly create an excel file extension .xlsx using openpyxl speficically based on the data above?我怎么可能根据上面的数据特别使用openpyxl创建一个excel文件扩展名.xlsx

result expected预期结果

在此处输入图像描述

Any help would be much appreciate?任何帮助将不胜感激?

One easy way to do this is to convert the people list shown above to pandas dataframe and use to_excel to write to a file.一种简单的方法是将上面显示的人员列表转换为 pandas 数据框并使用to_excel写入文件。 Code given below.下面给出的代码。 Note that if you don't specify sheet_name , it will write to default Sheet1 and if you don't use index=False , there will be an index column added in excel sheet column A. Rest is pretty straightforward.请注意,如果您不指定sheet_name ,它将写入默认 Sheet1 ,如果您不使用index=False ,则会在 Excel 工作表列 A 中添加一个索引列。Rest 非常简单。 Hope this helps.希望这可以帮助。 Note that pandas uses openpyxl under the hood to write to excel file.请注意,pandas 在后台使用openpyxl写入 excel 文件。

import pandas as pd
df = pd.DataFrame(people) #Convert people to list
df.to_excel('MyXL.xlsx', sheet_name = 'SheetName', index = False) #Write to myXL

Output Excel输出 Excel

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM