读取numb时出现xlrd错误

2024-10-02 16:27:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个小脚本来读取多个excel文件并将数据写入xml文件。我把剧本删掉了一点来解释出了什么问题。看起来像这样:

import glob, xlrd

xmlFile = 'example.xml'
xmlData = open(xmlFile, 'a')

for xlsfile in glob.glob('*.xls'):

    wb = xlrd.open_workbook(xlsfile)
    sh1 = wb.sheet_by_index(0)
    sh1c1 = sh1.col_values(1)   


    for cell in sh1c1: xmlData.write(cell + "\n")

只要excel文件中的单元格中只有文本,一切都会顺利。当其中一个单元格中有一个数字时,我得到一个错误:

^{pr2}$

它只在某些单元格和某些文件中包含一个数字。我已经读了很多关于float、integer和string的文章,但是我还没有找到一种方法将其应用到上面的代码中。我对python绝对是新手,我还不能把所有事情都弄清楚。有人想给我指出正确的方向吗?在

提前致谢。在


Tags: 文件inforcellxmlopenexcelglob
1条回答
网友
1楼 · 发布于 2024-10-02 16:27:11

正如评论者建议的那样,您需要将float转换为string才能使用+运算符:

for cell in sh1c1: xmlData.write(str(cell) + "\n")

或者,您可以将其改写为:

^{pr2}$

或者,如:

for cell in sh1c1: xmlData.write("%s\n" % cell)

相关问题 更多 >