Ask Your Question
4

How can I use Openpyxl to input dictionary data as a list into an Excel spreadsheet?

asked 2021-09-20 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-01-01 09:00:00 +0000

ladyg gravatar image

Here's an example of how to use Openpyxl to input dictionary data as a list into an Excel spreadsheet:

import openpyxl

# define the data as a dictionary with keys as headers and values as lists of values
data = {
    'Name': ['John', 'Mary', 'Bob'],
    'Age': [25, 30, 35],
    'Gender': ['Male', 'Female', 'Male']
}

# create a new workbook and select the active worksheet
workbook = openpyxl.Workbook()
worksheet = workbook.active

# set the headers in the first row
headers = list(data.keys())
for i in range(len(headers)):
    worksheet.cell(row=1, column=i+1, value=headers[i])

# input the values into the rows below the headers
values = list(data.values())
for i in range(len(values)):
    for j in range(len(values[i])):
        worksheet.cell(row=i+2, column=j+1, value=values[i][j])

# save the workbook
workbook.save('output.xlsx')

In this example, we first define the data as a dictionary with keys as headers and values as lists of values. Then, we create a new workbook and select the active worksheet. We set the headers in the first row using the keys of the dictionary, and input the values into the rows below the headers using the values of the dictionary. Finally, we save the workbook with the desired file name.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-20 11:00:00 +0000

Seen: 15 times

Last updated: Jan 01 '22