最新做测试案例时,需要使用*.xls文件作为输入,然后发现对于Excel文件,python有第三方库,官网地址为Working with Excel Files in Python,其中包含多个库。这里我选用的是xlrd,官网里有文档链接
xlrd
cell object(单元格对象)包含三个属性:ctype, value和xf_index.
Python中,cell(单元格)的类型和对应的类型值:
Type symbol | Type number | Python value |
---|---|---|
XL_CELL_EMPTY | 0 | empty string u” |
XL_CELL_TEXT | 1 | a Unicode string |
XL_CELL_NUMBER | 2 | float |
XL_CELL_DATE | 3 | float |
XL_CELL_BOOLEAN | 4 | int; 1 means TRUE, 0 means FALSE |
XL_CELL_ERROR | 5 | int representing internal Excel codes; for a text representation, refer to the supplied dictionary error_text_from_code |
XL_CELL_BLANK | 6 | empty string u”. Note: this type will appear only when open_workbook(…, formatting_info=True) is used. |
数据类型可以参考xlrd中的类型定义:
以下是xlrd模块的部分API使用实例:
book = xlrd.open_workbook('../test.xlsx')
print book.sheet_names()
#获取工作表对象
sheet = book.sheets()[0]
'''获取单元格的数据类型, python读取excel中单元格的内容返回的有5种类型:
ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error'''
print sheet.cell(1,0).ctype
# 获取单元格内容
print sheet.cell(0,0).value.encode('utf-8')
枚举类型
想使用枚举类型,但是Python自身不支持枚举类型,需要导入Enum模块:
from enum import Enum
''' '''
但是,导入Enum模块后却发现出错,见下图:
ImportError: No module named enum
后来发现,问题原因是:我装的python2.7,并没有自带Enmu模块(python3.4包含Enmu模块)
解决办法:安装Enmu模块,参考stackoverflow上的链接:
另外,Python的API查看方法:
在Windows下安装完python编译环境后,在开始菜单的Python目录下,有个Module Docs的连接。启动这个,然后选择open brower,就会出现一个本地服务器为你提供模块文档,这样就可以在浏览器中查看API。