openpyxl无法追加列表数据类型,一直显示TypeError:值必须为列表

时间:2018-12-11 07:15:58

标签: python openpyxl

这是我的代码

from openpyxl import Workbook
from openpyxl import load_workbook

def get_data_list(filename, sheetname):
    data = record = []
    # load excel file, read only mode
    wb = load_workbook(filename, read_only=True)
    # select sheet
    sheet = wb[sheetname]

    # write into data
    for row in sheet.rows:
        for cell in row:
            record.append(cell.value)
        data.append(record)
        record = []
    return data 

def write_data_list(data, filename, sheetname, no_header=False):
    wb = Workbook()
    sheet = wb.active
    sheet.title = sheetname

    # check header data
    if no_header :
        data.pop(0)

    # insert data
    for row in data:
        sheet.append(row)

    # save into file
    wb.save(filename)

data = get_data_list('excel/sample.xlsx','Sheet1')
# print(type(data))
write_data_list(data, 'data.xlsx', 'data')

我运行以下代码并产生以下错误消息:

Traceback (most recent call last):
  File "C:\Users\xxx\Projects\mergexl\rw.py", line 37, in <module>
    write_data_list(data, 'data.xlsx', 'data')
  File "C:\Users\xxx\Projects\mergexl\rw.py", line 31, in write_data_list
    sheet.append(row)
  File "C:\Users\xxx\.virtualenvs\mergexl-aotJkH4X\lib\site-packages\openpyxl\worksheet\worksheet.py", line 788, in append
    self._invalid_row(iterable)
  File "C:\Users\xxx\.virtualenvs\mergexl-aotJkH4X\lib\site-packages\openpyxl\worksheet\worksheet.py", line 872, in _invalid_row
    type(iterable))
TypeError: Value must be a list, tuple, range or generator, or a dict. Supplied value is <class 'str'>

如您所见,此错误在第33行显示了一个问题,该问题“ sheet.append(row)” 一直在询问列表数据类型输入。但是,变量 data 已经是一个列表。我已经通过

检查了数据类型

print(type(data))

然后输出为类“列表” 但是错误消息不断告诉您 data 类'str'

有什么解决办法吗?

1 个答案:

答案 0 :(得分:1)

data = record = []并没有按照您的想法做。

它将datarecord的名称绑定到同一列表对象。

第一次运行以下循环时,datarecord是相同的列表,并且在cell.value被添加之前,第一行record中的所有内容都已添加到该列表中。添加。

cell.value不是列表类的实例。

for row in sheet.rows:
    for cell in row:
        record.append(cell.value)
    data.append(record)
    record = []
return data 

您需要初始化数据并将其记录为单独的列表。

data = []

for row in sheet.rows:
    record = []
    for cell in row:
        record.append(cell.value)
    data.append(record)

return data