我在 xlrd 中从 Excel 读取特定单元格值时遇到困难。我正在读取的任何值(日期值)都将转换为数字。我知道有解决方案可以将其转换为 python 日期格式,但我可以直接读取 xlrd 中的字符串值吗?
3 回答
xlrd 不会将日期转换为浮点数。Excel 将日期存储为浮点数。
引用xlrd 文档(向下滚动一页):
Excel 电子表格中的日期
实际上,没有这样的事情。你所拥有的是浮点数和虔诚的希望。Excel日期有几个问题:
(1) 日期不作为单独的数据类型存储;它们存储为浮点数,您必须依赖 (a) Excel 中应用于它们的“数字格式”和/或 (b) 知道哪些单元格中应该有日期。该模块有助于 (a) 检查已应用于每个数字单元格的格式;如果它看起来是日期格式,则单元格被分类为日期而不是数字。
(2) ... 当使用此包的
xldate_as_tuple()
功能从工作簿转换数字时,您必须使用对象的datemode
属性Book
。
另请参阅Cell 类部分以了解单元格的类型,以及提取单元格类型(文本、数字、日期、布尔值等)的各种Sheet 方法。
查看python-excel.org以获取有关其他 Python Excel 包的信息。
好吧,正如你所说:
# reading from a xls file (no .xlsx files, no writing!)
import xlrd # install xlrd from http://pypi.python.org/pypi/xlrd
wb = xlrd.open_workbook("YOUR_FILE.xls") # xls file to read from
sh1 = wb.sheet_by_index(0) # first sheet in workbook
sh2 = wb.sheet_by_name('colors') # sheet called colors
# print all rows in first sheet
print "content of", sh1.name # name of sheet
for rownum in range(sh1.nrows): # sh1.nrows -> number of rows (ncols -> num columns)
print sh1.row_values(rownum)
# rowx and colx (x for Excel) start at 1!
print "row3 col 2:", sh1.cell(rowx=3,colx=2).value
col = sh1.col_values(0) # column 0 as a list of string or numbers
print '"A" column content:' # python index 0, 1.colunm, called A
for cell in col: print cell
print sh1.col_values(1) # 2. column, note mix of string (header) and numbers!
对于这个例子,XLS 是:
表 1:列表
name latitude longitude status color date
Mount Hood 45.3736 121.6925 active red 01-ene-01
Mount Jefferson 44.6744 121.7978 dormant yellow 23-sep-05
Three-Fingered 44.478 121.8442 extinct green
Mount Washington 4.3325 121.8372 extinct green
South Sister 44.1036 121.7681 active red
Diamond Peak 43.5206 122.1486 extinct green
Mount Thielsen 43.1531 122.0658 extinct green
Mount Scott 42.923 122.0163 dormant yellow
Mount McLoughlin 2.445 122.3142 dormant yellow
表 2:颜色
status color
active red
dormant yellow
extinct green
Excel 在内部和 .xls 文件中将日期存储为数字,然后在显示时对其进行相应的格式化。因此,如果您用xlrd天真地阅读它们,您将得到数字或字符串。您应该做的是检查单元格的类型,然后自己转换数字。使用xlrd的内置函数,例如xldate_as_tuple()
,或您自己的函数。
有关更多详细信息,请参阅此问题。