Python xlrd 读取为字符串
我在用xlrd读取Excel中的某个单元格值时遇到了困难。我读取的值(日期值)总是被转换成数字。我知道有办法把它转换成Python的日期格式,但我想知道在xlrd中能不能直接读取到字符串值?
3 个回答
Excel在内部和.xls文件中把日期存储为数字,然后在显示时再进行格式化。所以,如果你用xlrd直接读取这些日期,你得到的可能是数字或者字符串。你需要做的是检查单元格的类型,然后自己把数字转换成日期。你可以使用xlrd自带的函数,比如xldate_as_tuple()
,或者自己写一个函数来处理。
想了解更多细节,可以参考这个问题。
好吧,正如你所说:
# 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
xlrd 并不会把日期转换成浮点数。其实,Excel 是把日期存储为浮点数的。
引用自 xlrd 的文档(向下滚动页面):
Excel 表格中的日期
实际上,Excel 中并没有真正的日期。你看到的只是浮点数和一些美好的期望。Excel 日期存在几个问题:
(1) 日期并不是以单独的数据类型存储的;它们是以浮点数的形式存储的。你需要依赖于 (a) 在 Excel 中应用的“数字格式”,或者 (b) 知道哪些单元格应该包含日期。这个模块通过检查每个数字单元格应用的格式来帮助解决 (a) 的问题;如果它看起来像日期格式,那么这个单元格就会被归类为日期,而不是数字。
(2) ... 当使用这个包中的
xldate_as_tuple()
函数从工作簿中转换数字时,你必须使用Book
对象的datemode
属性。
还可以查看 Cell 类 的部分,了解单元格的类型,以及各种 Sheet 方法,这些方法可以提取单元格的类型(文本、数字、日期、布尔值等)。
想了解其他 Python Excel 包的信息,可以访问 python-excel.org。