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

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

 

Function ImportAllSheets(ByVal FileName)

       Dim oExcel, oBook

 

       'Launch excel

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

 

       'Open the file in read only mode

       Set oBook = 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 oBook = Nothing

 

       'Quit Excel

       oExcel.Quit

       Set oExcel = Nothing

End Function

 

 

Function IfDataSheetExist(ByVal SheetName)

       IfDataSheetExist = True

       On error resume next

       Dim oTest

       Set oTest = DataTable.GetSheet(SheetName)

       If err.number Then IfDataSheetExist = False

       On error goto 0

End Function

 

 

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页