Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.