这是我的代码from openpyxl import Workbookfrom openpyxl import load_workbookdef 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”有什么解决办法吗?
1 回答
Qyouu
TA贡献1786条经验 获得超11个赞
data = record = [] 没有做你认为它做的事情。
它绑定data并record命名到同一个列表对象。
第一次下面的循环运行,data并且record是同一个列表,所有在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
添加回答
举报
0/150
提交
取消