简体   繁体   中英

how to loop through each row in excel spreadsheet using openpyxl

I would like to make the first column of each row in an excel spreadsheet as a key and rest of the values in that row as its value so that I can store them in a dictionary. The problem is, when I loop through the rows and columns all the row values are getting stored in every key.

import openpyxl

from openpyxl import load_workbook

file = "test.xlsx"

#load the work book
wb_obj = load_workbook(filename = file)

wsheet = wb_obj['test']

#dictionary to store data
dataDict = {}

value = []

row_count = wsheet.max_row
col_count = wsheet.max_column

# loop to get row and column values
for i in range(2, row_count+1):
    for j in range(i, col_count+1):
        key   = wsheet.cell(row=i, column=1).value
        print (key)
        value.append(wsheet.cell(row=i, column=j).value)
        print (value)

    dataDict[key] = value

#prompt user for input
userInput = input("Please enter an id to find a person's details: ")

print (dataDict.get(int(userInput)))

data in spreadsheet: 在此处输入图片说明

Result I'm expecting: {1: ['John', 'Doe', 4567891234, 'johndoe@jd.ca'], 2: ['Wayne 'Kane', 1234567891, 'wd@wd.ca']}

Result I got: {1: ['John', 'Doe', 4567891234, 'johndoe@jd.ca', 'Kane', 1234567891, 'wd@wd.ca'], 2: ['John', 'Doe', 4567891234, 'johndoe@jd.ca', 'Kane', 1234567891, 'wd@wd.ca']}

Openpyxl already has a proper way to iterate through rows using worksheet.iter_rows() . You can use it to unpack the first cell's value as the key and the values from the other cells as the list in the dictionary, repeating for every row.

from openpyxl import load_workbook

file = "test.xlsx" #load the work book
wb_obj = load_workbook(filename = file)
wsheet = wb_obj['test']
dataDict = {}

for key, *values in wsheet.iter_rows():
    dataDict[key.value] = [v.value for v in values]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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