0

I have a problem with importing data from the spreadsheet. I'm trying create list containing all data. But only last row is added to list.

from openpyxl import load_workbook

path = "excel.xlsx"
l_data = load_workbook(path)
sheet = l_data.active
c_row = sheet.max_row
c_column = sheet.max_column
out_data=[]
dict={}
for a in range(1, c_row + 1):
    for b in range(1, c_column + 1):
        ob = sheet.cell(row=a, column=b)
        dict[b] = ob.value
    out_data.append(dict)

I need such output data: [ {1:"row1_call1",2:"row1_call2"},{1:"row2_call1",2:"row2_call2"} ]

bobi
  • 61
  • 6

1 Answers1

0

Try that one:

from openpyxl import load_workbook

path = "excel.xlsx"
l_data = load_workbook(path)
sheet = l_data.active
c_row = sheet.max_row
c_column = sheet.max_column
out_data=[]
dict={}
for a in range(1, c_row + 1):
    for b in range(1, c_column + 1):
        ob = sheet.cell(row=a, column=b)
        dict[b] = ob.value

    out_data.append(str(dict))

print(out_data)

It changes type of dict values. So only this line changes from:

out_data.append(dict)

to:

out_data.append(str(dict))

Check that site if you want know more appending dict to list: python: Appending a dictionary to a list - I see a pointer like behavior

So this is also working:

out_data.append(dict.copy())
N00b
  • 148
  • 11