How to import entire sheet to list via openpyxl

允我心安 提交于 2019-12-13 03:46:17

问题


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"} ]


回答1:


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())


来源:https://stackoverflow.com/questions/54805903/how-to-import-entire-sheet-to-list-via-openpyxl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!