QTP对Excel的操作(EOM) 类封装

接上一篇,我把Excel读取的出来的数据封装成一个Dictionary对象,这样调用起来比较方便。调用的时候根据输入的所需要第几行数据取得数据

下面是代码:

Class ExcelDic
    Public Dic  'Dictionary对象存放查询到指定行的Excel结果集
    'Public DicDictionary  '存放所有的行记录,以行号作为Key值
    Public FilePath  'Excel文件存放路径
    Public SheetName   '要查询的Sheet名称,即表名
    Private RowIndex   '要查询的数据所在行

    Public Default Function Load(pth,sheet,row)
       Set Dic = CreateObject("Scripting.Dictionary")
       'Set DicDictionary = CreateObject("Scripting.Dictionary")
       FilePath = pth
       SheetName = sheet
       RowIndex = row
       GetContext
       Set Load = Dic
    End Function

    Private Function GetContext()
        Dim connStr,sqlStr
        Dim conn,rst
        Set conn = CreateObject("ADODB.CONNECTION")
        Set rst = CreateObject("ADODB.RECORDSET")

        '连接数据库的字符串,后面的“HDR=yes”需要注意,它的意思是把Excel表第一行作为字段名,第二行开始方是有效数据。
        'HDR=no则反之,从第一行开始就看做有效数据
        '2007中新的Provider为Microsoft.ACE.OLEDB.12.0,之前的2003为Microsoft.Jet.OLEDB.4.0
        connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & FilePath & ";Extended Properties=""Excel 8.0;HDR=yes;IMEX=1"""
        sqlStr = "select * from [" & SheetName & "$]"
        conn.Open connStr
        Set rst = conn.Execute(sqlStr)
        rst.MoveFirst
        For i=2 to RowIndex
            If rst.EOF Then
                Exit For
            End If            
            rst.MoveNext
        Next
        If rst.EOF Then
            msgbox "Record Set 游标越界"
            Exit Function
        End If
        For i = 0 to rst.Fields.Count-1                
            Dic.Add rst.Fields.Item(i).Name,rst.Fields.Item(i).Value                
        Next        
    End Function
End Class


'测试代码
Set aa = new ExcelDic
Set myDic = aa.Load("d:\1.xlsx","sunyu",1)
msgbox myDic("PWD")
msgbox myDic("Age")

原文地址:https://www.cnblogs.com/ryansunyu/p/2685155.html