2

我正在编写一个函数,用于从 xls/xlsx 文件中读取数据并插入到 db 中。但问题是从 xls 文件的单元格中读取数据后,该值变为浮点类型。

以下是我来自 xls 文件的示例数据:

Zip     Zone
35096       
31723   1
35963       
36037   D 21
36849   HANDLE

我正在使用from openpyxl.reader.excel import load_workbook读取 xls 文件。当我将这些值插入 DB 时,从ZipZone列读取值后,所有数值都变为浮点类型,但应保存为字符串。以上 2 db 列的类型为VARCHAR

从终端中的 xls 文件读取后,我还打印了上述 2 列的值,结果如下:

压缩

==========
<type 'float'>
35096.0
==========
<type 'float'>
31723.0
==========
<type 'float'>
35963.0
==========
<type 'float'>
36037.0
==========
<type 'float'>
36849.0

==========
<type 'NoneType'>
==========
<type 'float'>
1.0
==========
<type 'NoneType'>
==========
<type 'unicode'>
D 21
==========
<type 'unicode'>
HANDLE

我的代码

try:
    book = load_workbook(filename=file_path, use_iterators=True)
    ws = book.worksheets[0]
except:
    return 'Error message'


for row in (ws.iter_rows()):
    zip = row[0].internal_value
    zone = row[1].internal_value

其他信息:我正在使用 python 2.6 和 Ubuntu 机器如何解决这个问题。

4

1 回答 1

0

如果 zip 是一个序列尝试

zip = [str(fl) for fl in row[0].internal_value[:]]
于 2013-08-29T10:14:09.113 回答