Python openpyxl:在二维列表中追加单元格值

Python openpyxl: append cell values on a 2d list

我目前正在学习Python。我正在使用 Python35。 基本上我有一个 excel sheet 具有固定数量的列和行(包含数据),我想使用 append.

将这些值保存在二维列表中

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

import openpyxl
Values=[[]]

MaxColumn=sheet.max_column
MaxRow=sheet.max_row

for y in range (10,MaxRow):#Iterate for each row.
 for x in range (1,MaxColumn):#Iterate for each column.
  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)

您必须有一些重新定义 Values 对象的代码,但无论如何您都可以执行 list(sheet.values).

尝试以下操作:

# 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 objectindex y 处的 int 值。