如何从Excel文件中导入所有Sheet到DataTable中?

上一篇 / 下一篇  2011-03-29 16:55:51 / 个人分类:QTP

如果需要从外部存储的测试数据文件例如 Excel 中导入 Sheet 页到 DataTable 中,并且判断 DataTable 中是否存在指定的 Sheet ,如果不存在则添加 Sheet 。可以例如 DataTable 对象的 GetSheet 、 AddSheet 以及 Excel 的 COM 对象编程来实现:

 

Function ImportAllSheets(ByVal FileName)

       Dim oExcel, oBook

 

       'Launch excel

       Set Excel = GetObject("", "Excel.Application")

 

       'Open the file in read only mode

       Set Book = oExcel.WorkBooks.Open(FileName,,True)

 

       'Enumerate through all the sheets present in the file

       For each oSheet in oBook.WorkSheets

 

              'Check if a DataTable with current name already exists

              If Not IfDataSheetExist(oSheet.Name) Then

                     'DataTable cannot be imported if the sheet does not exist

                     DataTable.AddSheet oSheet.Name

              End If

 

              'Import the sheet

              DataTable.ImportSheet FileName, oSheet.Name,oSheet.Name

       Next

 

       Set Book = Nothing

 

       'Quit Excel

       oExcel.Quit

       Set Excel = Nothing

End Function

 

 

Function IfDataSheetExist(ByVal SheetName)

       IfDataSheetExist = True

       On error resume next

       Dim oTest

       Set Test = DataTable.GetSheet(SheetName)

       If err.number Then IfDataSheetExist = False

       On error goto 0

End Function

 



TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-04-30  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 8410
  • 日志数: 27
  • 建立时间: 2011-03-28
  • 更新时间: 2011-05-12

RSS订阅

Open Toolbar