您的位置:首页 > 编程语言

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

2010-01-02 17:35 816 查看
如果需要从外部存储的测试数据文件例如
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

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息