Python - TypeError: 'Cell' object is not iterable

Python - TypeError: 'Cell' object is not iterable

我想做的基本上是根据我从列表中获得的数据编写一个新的 excel 文件。列表的内容是我尝试使用 xlsxwriter(特别是 xlsx,因为我使用的是 xlsx)在新 excel 文件中写入的行内容。假设我有下面的代码片段,它会产生错误:

TypeError: 'Cell' object is not iterable

整个堆栈跟踪在写入事件期间指出了这一点。

Traceback (most recent call last):
File "Desktop/excel-copy.py", line 33, in <module>
    sheet.write_row(row_index, col_index, cell_value)
  File "/usr/local/lib/python2.7/dist-packages/xlsxwriter/worksheet.py", line 64, in cell_wrapper
    return method(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/xlsxwriter/worksheet.py", line 989, in write_row
    for token in data:
TypeError: 'Cell' object is not iterable


import xlrd
import xlsxwriter

new_workbook = xlsxwriter.Workbook()
sheet = new_workbook.add_worksheet('stops')

#copy all row and column contents to new worksheet
for row_index, row in enumerate(ordered_list_stops):
    for col_index, cell_value in enumerate(row):
        print("WRITING: " + str(cell_value) + "AT " + str(row_index)+ " " + str(col_index))
        sheet.write_row(row_index, col_index, cell_value)

new_workbook.save('output.xlsx')

我不能完全指出 cell_value 是否是原因。我试着把它打印出来,结果是这样的:

WRITING: text:u'4977'AT 0 0

问题是 write_row 获取一个值列表(或其他可迭代的),而您传递的是单个 Cell 对象 (cell_value)。

您要么想使用 sheet.write(row_index, col_index, cell_value),要么跳过内部 for 循环并使用 sheet.write_row(row_index, 0, row)