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

这是我的代码


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)”不断询问列表数据类型输入。但是,变量数据已经是一个列表。我已经检查了数据类型


print(type(data))

那么输出是类“list”, 但错误消息一直告诉数据是类“str”


有什么解决办法吗?


BIG阳
浏览 1223回答 1
1回答

Qyouu

data = record = [] 没有做你认为它做的事情。它绑定data并record命名到同一个列表对象。第一次下面的循环运行,data并且record是同一个列表,所有在cell.value第一行中被添加到列表之前record加入。cell.value 不是列表类的实例。for row in sheet.rows:&nbsp; &nbsp; for cell in row:&nbsp; &nbsp; &nbsp; &nbsp; record.append(cell.value)&nbsp; &nbsp; data.append(record)&nbsp; &nbsp; record = []return data&nbsp;您需要将数据和记录初始化为单独的列表。data = []for row in sheet.rows:&nbsp; &nbsp; record = []&nbsp; &nbsp; for cell in row:&nbsp; &nbsp; &nbsp; &nbsp; record.append(cell.value)&nbsp; &nbsp; data.append(record)return data&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python