TypeError:Value必须是列表,元组,范围或生成器或dict

时间:2015-06-16 19:03:50

标签: python xml excel typeerror openpyxl

我创建了一个脚本,通过正则表达式提取XML值,然后附加到Excel工作表。然后我添加了一个元素树方法来通过标记名称获取值。我还想将该值附加到同一个XLSX表。

我收到此错误:

Traceback (most recent call last):
  File "C:\Path\To\Desktop\excels.py", line 23, in <module>
    ws.append(agreement)
  File "C:\Python34\lib\site-packages\openpyxl\worksheet\worksheet.py", line 763, in append
    self._invalid_row(iterable)
  File "C:\Python34\lib\site-packages\openpyxl\worksheet\worksheet.py", line 768, in _invalid_row
    type(iterable))
TypeError: Value must be a list, tuple, range or generator, or a dict. Supplied value is <class 'str'>

这是我发现并正在测试的示例elementTree代码。

from openpyxl import Workbook
import xml.etree.ElementTree as ET

xmlfile = 'test.xml'
element_tree = ET.parse(xmlfile)
root = element_tree.getroot()
agreement = root.find(".//tag").text
#variable = int(agreement)

print (agreement)


wb = Workbook()
kevin = ["1", "2", "3"]

# grab the active worksheet
ws = wb.active

# Data can be assigned directly to cells
ws['A1'] = 42

# Rows can also be appended
ws.append(agreement)
ws.append(kevin)


# Save the file
wb.save("sample.xlsx")

1 个答案:

答案 0 :(得分:3)

WorkSheet实例上的

append()函数接收一个iterable作为参数,而您传入​​一个字符串(agreement变量)。

相反,你的意思是:

ws.append([42, agreement])

或:

ws.append([agreement])