2017-03-09 138 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值。