【问题标题】:Convert data to string after reading from a xls or xlsx file in python从python中的xls或xlsx文件读取后将数据转换为字符串
【发布时间】:2013-09-01 14:30:44
【问题描述】:

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

以下是 xls 文件中的示例数据:

Zip     Zone
35096       
31723   1
35963       
36037   D 21
36849   HANDLE

我正在使用from openpyxl.reader.excel import load_workbook 来读取 xls 文件。当我将这些值插入数据库时​​,从 Zip 和 Zone 列读取值后,所有数值都变为浮点类型,但应保存为字符串。以上2db列的类型为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 机器 如何解决这个问题。

【问题讨论】:

  • 您能展示一下您用于读取 excel 文件的代码吗?
  • @alecxe:我已将代码添加到问题中。
  • 如果您只是将值转换为字符串:zip = str(row[0].internal_value) 和 str(row[1].internal_value)?
  • 我已经尝试使用 str() 转换数据,但它不起作用。

标签: python django xls xlsx openpyxl


【解决方案1】:

如果 zip 是一个序列尝试

zip = [str(fl) for fl in row[0].internal_value[:]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    相关资源
    最近更新 更多