如何通过openpyxl将整个工作表导入列表 [英] How to import entire sheet to list via openpyxl
本文介绍了如何通过openpyxl将整个工作表导入列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从电子表格导入数据时遇到问题. 我正在尝试创建包含所有数据的列表.但是只有最后一行被添加到列表中.
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)
我需要这样的输出数据: [{1:"row1_call1",2:"row1_call2"},{1:"row2_call1",2:"row2_call2"}]
I need such output data: [ {1:"row1_call1",2:"row1_call2"},{1:"row2_call1",2:"row2_call2"} ]
推荐答案
尝试一个:
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)
收件人:
out_data.append(str(dict))
如果您想了解更多将字典追加到列表的信息,请检查该站点: python:将字典添加到列表-我看到了类似行为的指针
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
所以这也起作用:
out_data.append(dict.copy())
这篇关于如何通过openpyxl将整个工作表导入列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文