AttributeError:'float'对象没有属性'encode'3

时间:2014-12-24 09:11:55

标签: python

我有用于读取excel到xml格式的python脚本,但它显示了一些错误

val = sh.row_values(row)[i].encode("utf-8")
Attribute Error : 'float' object has no attribute 'encode'

这是我的代码:

import xlrd

wb = xlrd.open_workbook("my_excel_file.xlsx")
sh = wb.sheet_by_index(0)
tags = [n.replace(" ", "").lower() for n in sh.row_values(0)]

result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<myItems>\n" 

for row in range(1, sh.nrows): 
    result += "  <item>\n"
    for i in range(len(tags)):    
       tag = tags[i].encode("utf-8")
       val = sh.row_values(row)[i].encode("utf-8")   
       result += "    <%s>%s</%s>\n" % (tag, val, tag)    
    result += "  </item>\n"

result += "</myItems>"   

f = open("myfile.xml", "w")
f.write(result)
f.close()

1 个答案:

答案 0 :(得分:4)

你已经在那里需要一个字符串。像这样转换它:

   val = str(sh.row_values(row)[i]).encode("utf-8")