这是以前为了在测试工具中方便的读取Excel数据写的脚本(一个轻量级框架的一部分)。总体思路是:利用Excel的com接口,把数据读取到字典(键值对,也就是测试字段对应测试数据)中,然后在通过键值对的key把测试数据读取出来。(这种方法虽然比较简陋,但是胜在简单易用)。下面就具体说明一下:
首先,我们先看一下Excel中的测试数据格式,
Field DataType DataValue DataValue
姓名 string 姓名1 姓名2
性别 string 男 女
年龄 int 34 45
第一列 字段名称
第二列 数据类型
第三列及之后 测试数据
具体代码如下:
Dim objexcel 'excel对象
Dim objworkbook 'excel的workbook对象
Dim objsheet 'sheet对象
Dim objDictionary '字典对象
'=========================
'获取sheet对象
'sheetname: sheet名称
'path: 文件路径
'=========================
Function Getexcelobject(sheetname,filepath)
Set bjexcel = CreateObject("excel.application")
Set bjworkbook = objexcel.Workbooks.Open(filepath)
Set bjsheet = objworkbook.Sheets(sheetname)
End Function
'========================
'关闭excel
'========================
Function ExcelColse()
objworkbook.Close
End Function
'========================
'获取测试字段与默认测试数据的键对数组
'========================
Function GetDictionary()
Set bjDictionary = CreateObject("Scripting.Dictionary")
x=2
Do While Not (objsheet.cells(x,1).value ="")
objDictionary.Add CStr(objsheet.cells(x,1)),CStr(objsheet.cells(x,3))
x=x+1
Loop
End Function
'========================
'获取测试字段与指定测试数据的键对数组
'========================
Function GetSpecDictionary(y)
Set bjDictionary = CreateObject("Scripting.Dictionary")
x=2
Do While Not (objsheet.cells(x,1).value ="")
objDictionary.Add CStr(objsheet.cells(x,1)),CStr(objsheet.cells(x,y))
x=x+1
Loop
End Function
'=========================
'获取默认测试数据值
'field:AUT字段
'=========================
Function Getvalue(field)
GetDictionary()
Getvalue = objDictionary(field)
End Function
'=========================
'获取测试数据的数量
'=========================
Function Getvaluenumber()
GetDictionary()
Getvaluenumber = objDictionary.Count
End Function
'========================
'获取指定列数据,field为字段名,colnumber为列值
'========================
Function Getspecvalue(field,colnumber)
GetSpecDictionary(colnumber)
Getspecvalue = objDictionary(field)
End Function
如果想读取默认测试数据,也就是读取第三列,需如下进行:
Call Getexcelobject("sheet1","E:\TestData\查询.xls")
WScript.Echo Getvalue("姓名")
如果想读取任意列的测试数据,需:
Call Getexcelobject("sheet1","E:\TestData\查询.xls")
WScript.Echo Getspecvalue("姓名",4)