python - xlrd 单元格的原始值

标签 python excel xls xlrd

我正在使用 xlrd 读取 xls 文件。问题是,当 xlrd 读取这样的值时 "12/09/2012",我得到这样的结果 "xldate:41252.0"。当我使用 xlrd.xldate_as_tuple 时,我得到了这个结果:

(2016, 12, 10, 0, 0, 0)

我的代码:

curr_row = -1
while curr_row < num_rows:
    curr_row += 1
    row = worksheet.row(curr_row)     
        for x in xrange(num_cols):
            field_type = worksheet.cell_type(curr_row, x)
            if field_type == 3: # this is date
                field_value = worksheet.cell_value(curr_row, x)
                print worksheet.cell(curr_row, x).value
                print xlrd.xldate_as_tuple(field_value, 1)

结果:

41252.0
(2016, 12, 10, 0, 0, 0)

这两个结果对我来说都是错误的。如何使用 xlrd 获取原始单元格值“12/09/2012”?

最佳答案

根据docstring ,您应该将工作簿的日期模式作为第二个参数传递给 xldate_as_tuple:

from datetime import datetime
import xlrd


book = xlrd.open_workbook("test.xls")
sheet = book.sheet_by_index(0)
a1 = sheet.cell_value(rowx=0, colx=0)

print a1  # prints 41252.0
print xlrd.xldate_as_tuple(a1, 1)  # prints (2016, 12, 10, 0, 0, 0)

a1_tuple = xlrd.xldate_as_tuple(a1, book.datemode)  
print a1_tuple  # prints (2012, 12, 9, 0, 0, 0)

a1_datetime = datetime(*a1_tuple)
print a1_datetime.strftime("%m/%d/%Y")  # prints 12/09/2012

关于python - xlrd 单元格的原始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16229610/

相关文章:

python - 按列分组并找到每组的最小值和最大值

python - 玛雅Python : offsetting a sound file

python - Pandas:将数据框写入 Excel (.xls) 文件问题

ruby-on-rails - 如何用roo打开xls文件

javascript - 大数据时导出为 .xls 文件不起作用

python - 我如何在 python 中连接到 Microsoft sql server 2008

python - Python3中的打印功能

vba - 使用 VBA 自动将 VBProject 引用添加到 PowerPoint 库,具体取决于 PC 运行的 Office 版本

excel - 删除重复项,但尊重案例

excel - 创建全局文件路径