我有一个代码,用于从excel检索每个数据以更新dbf文件。我使用Microsoft.Office.Interop.Excel读取每个列范围的数据。 现在我想用oledb更改连接excel .. 如何检索每列的数据并将其设置为变量? 这是我的Microsoft.Office.Interop.Excel。
的代码 xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Open(xlsName)
xlWorkSheet = xlWorkBook.Worksheets("sheet1")
xlRange = xlWorkSheet.UsedRange
endrow = xlRange.Rows.Count
For rCnt = 3 To endrow
Empno = xlRange.Cells(rCnt, 1).Value
totalhrs = xlRange.Cells(rCnt, 3).Value
latehr = xlRange.Cells(rCnt, 4).Value
Next
xlWorkBook.Close()
xlApp.Quit()
这是我的oledb连接。在连接之后,我真的不知道我该怎么做才能获得数据。请帮助我...我希望stackoverflow中的某个人可以帮助我。
Dim xlsConnect As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Try
If (Path.GetExtension(xlsName) = ".xls") Then
xlsConnect = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & xlsName & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2""")
ElseIf (Path.GetExtension(xlsName) = ".xlsx") Then
xlsConnect = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & xlsName & ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';")
End If
MyCommand = New System.Data.OleDb.OleDbDataAdapter("Select * from [Sheet1$]", xlsConnect)
'looping data should be here
xlsConnect.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
答案 0 :(得分:1)
假设您将在datagridview中显示您的详细信息。您可以尝试这段代码:
MyCommand.TableMappings.Add("Table", "TestTable")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
DataGridView1.DataSource = DtSet.Tables(0)
MyConnection.Close()
如果要使用变量,则必须循环遍历数据集:
dim i as integer = 0
for i = 0 to dtset.tables(0).rows.count-1
'Add values to your variable
next