2017-03-09 139 views
0

我目前正在学习Python。我正在使用Python35。 基本上我有一个固定数量的列和行(包含数据)的Excel工作表,我想用append将这些值保存在一个2D列表中。Python openpyxl:在二维列表上附加单元格值

我目前将数据保存在一维列表中。这是我的代码:

import openpyxl 
 
Values=[[]] 
 

 
MaxColumn=sheet.max_column 
 
MaxRow=sheet.max_row 
 

 
for y in range (10,MaxRow):#Iterate for each row. 
 
\t for x in range (1,MaxColumn):#Iterate for each column. 
 
\t \t Values.append(sheet.cell(row=y,column=x).value) 
 
    
 
#I have tried with the following: 
 
Values[y].append(sheet.cell(row=y,column=x).value) 
 

 
Traceback (most recent call last): 
 
    File "<pyshell#83>", line 4, in <module> 
 
    Values[y].append(sheet.cell(row=y,column=x).value) 
 
AttributeError: 'int' object has no attribute 'append'

for x in range (1,MaxColumn): 
    #print(sheet.cell(row=y,column=x).value) 
    Values.append(sheet.cell(row=y,column=x).value) 

回答

0

你必须有一些代码,重新定义了Values对象,但在任何情况下,你可以这样做list(sheet.values)

+0

'list(sheet.values)'将返回一个元组列表(值) – stovfl

+0

这就是请求。 –

0

尝试以下操作:

# Define a list 
list_2d = [] 
# Loop over all rows in the sheet 
for row in ws.rows: 
    # Append a list of column values to your list_2d 
    list_2d.append([cell.value for cell in row]) 

print(list_2d) 

你回溯错误:

Values[y].append(
AttributeError: 'int' object has no attribute 'append' 

Values[y]不是list object,在你list object索引j它的一个int值。