这是我的代码
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”
有什么解决办法吗?
Qyouu
相关分类