【问题标题】:Reading numeric Excel data as text using xlrd in Python在 Python 中使用 xlrd 将数字 Excel 数据读取为文本
【发布时间】:2011-02-13 23:05:52
【问题描述】:

我正在尝试使用 xlrd 读取 Excel 文件,我想知道是否有办法忽略 Excel 文件中使用的单元格格式,而只是将所有数据导入为文本?

这是我目前使用的代码:

import xlrd

xls_file = 'xltest.xls'
xls_workbook = xlrd.open_workbook(xls_file)
xls_sheet = xls_workbook.sheet_by_index(0)

raw_data = [['']*xls_sheet.ncols for _ in range(xls_sheet.nrows)]
raw_str = ''
feild_delim = ','
text_delim = '"'

for rnum in range(xls_sheet.nrows):
    for cnum in range(xls_sheet.ncols):
        raw_data[rnum][cnum] = str(xls_sheet.cell(rnum,cnum).value)

for rnum in range(len(raw_data)):
    for cnum in range(len(raw_data[rnum])):
        if (cnum == len(raw_data[rnum]) - 1):
            feild_delim = '\n'
        else:
            feild_delim = ','
        raw_str += text_delim + raw_data[rnum][cnum] + text_delim + feild_delim

final_csv = open('FINAL.csv', 'w')
final_csv.write(raw_str)
final_csv.close()

此代码是有效的,但某些字段(例如邮政编码)是作为数字导入的,因此它们具有十进制零后缀。例如,Excel文件中是否有“79854”的邮政编码,将其导入为“79854.0”。

我已尝试在此 xlrd spec 中找到解决方案,但未成功。

【问题讨论】:

    标签: python excel csv xls xlrd


    【解决方案1】:

    这是因为 Excel 中的整数值在 Python 中作为浮点数导入。因此,sheet.cell(r,c).value 返回一个浮点数。尝试将值转换为整数,但首先要确保这些值在 Excel 中是整数:

    cell = sheet.cell(r,c)
    cell_value = cell.value
    if cell.ctype in (2,3) and int(cell_value) == cell_value:
        cell_value = int(cell_value)
    

    全部在xlrd spec

    【讨论】:

    • xlrd 报告它的发现。 Excel 中唯一的“整数值”是小数部分为零的浮点数。 Excel 及其用户只是没有将整数作为单独类型的概念。 XLS 文件中某些 RK 单元记录中包含的整数仅仅是序列化的产物,xlrd 正确地将它们转换为浮点数。
    【解决方案2】:

    我知道这不是问题的一部分,但我会摆脱 raw_str 并直接写入您的 csv。对于大文件(10,000 行),这将节省大量时间。

    你也可以去掉raw_data,只使用一个for循环。

    【讨论】:

      猜你喜欢
      • 2019-04-17
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      相关资源
      最近更新 更多