2012-12-31 86 views
0

我寫了一個小腳本來讀取多個excel文件並將數據寫入xml文件。我解釋了一下腳本來解釋出了什麼問題。它看起來像這樣:xlrd錯誤讀取數

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文件中的單元格中只有文本。當其中一個單元格中有數字時;我收到一個錯誤:

Traceback (most recent call last): 
    File "test.py", line 14, in <module> 
    for cell in sh1c1: xmlData.write(cell + "\n") 
TypeError: unsupported operand type(s) for +: 'float' and 'str' 

它只在某些單元格和某些文件中包含數字。我已經閱讀了很多關於浮點數,整數和字符串的知識,但是我還沒有找到在上面的代碼中應用它的方法。我對python來說是全新的,而且我無法把所有東西都放在頭上。有人想讓我指出正確的方向嗎?

非常感謝提前。

+2

由於回溯告訴你:'cell'是一個浮點數,你不能連接它與一個字符串...所以將浮點數轉換爲str首先。 –

回答

0

正如評論者建議,你需要你的浮子轉換爲字符串使用+操作:

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

或者,你可以把它改寫爲:

for cell in sh1c1: xmlData.write("{0}\n".format(cell)) 

或者,如:

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

工程就像一個魅力。只有當一個單元格包含「3」時,才返回「3.0」。我得到的固定通過寫作:在sh1c1 細胞: \t \t如果細胞== STR(小區): \t \t \t xmlData.write( 「{0} \ n」 個.format(小區)) \t \t else: \t \t \t xmlData.write(「{0} \ n」.format(int(cell))) 再次感謝! –