2009-06-12 70 views

回答

1

亚历克斯 - 这里是一些旧的代码我挖出来查询Excel中。这里非常基本的场景。不要关注糟糕的错误处理和缺乏'使用'构造。

Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0" & _ 
          ";Data Source=" & ExcelFile & _ 
          ";Extended Properties=Excel 8.0;" 

Dim conn As OleDbConnection = Nothing 
Dim dt As System.Data.DataTable = Nothing 
Dim excelDataSet As New DataSet() 

Try 

    conn = New OleDbConnection(connString) 

    conn.Open() 
    dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing) 

    If dt Is Nothing Then 
     Return Nothing 
    End If 

    Dim excelSheets(dt.Rows.Count) As String 
    Dim i As Integer = 0 
    For Each row As DataRow In dt.Rows 
     excelSheets(i) = row("TABLE_NAME").ToString 
     System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1) 
     If i = SheetNumber Then 
      Exit For 
     End If 
    Next 

    Using excelCommand As New OleDbCommand("Select * from [" & excelSheets(SheetNumber - 1) & "]", conn) 
     Using excelAdapter As New OleDbDataAdapter(excelCommand) 
      excelAdapter.Fill(excelDataSet) 
     End Using 
    End Using 


Catch ex As OleDbException 
    Throw 
Catch ex As Exception 
    Throw 
Finally 

    conn.Close() 

    If conn IsNot Nothing Then 
     conn.Dispose() 
    End If 

    If dt IsNot Nothing Then 
     dt.Dispose() 
    End If 

End Try 

Return excelDataSet 
1

直接从.NET使用Excel Object Model

+0

嘿,你能告诉我一个如何打开excel文件并阅读它的例子吗? – 2009-06-12 23:11:11

1

您可以使用ado.net来通过OLEDB JET 4提供

这只是打开Excel文件作为文件流,而不是打开实际的Excel电子表格从Excel电子表格读取。

或者,您可以使用com-interop并简单地将应用程序对象visible属性设置为false。

http://www.connectionstrings.com/excel

有一个问题要注意使用与任何办公应用.NET和COM互操作时是,如果你试图打开该应用程序谁比实际用户更多的是窗口服务的用户那么您将需要以该用户的身份登录到Windows,并以该用户的身份打开相关应用程序,以便所有注册表条目都可以针对Office应用程序的某些功能进行正确更新。

0

如果你有一个不需要动态的更简单的Excel电子表格,我想你可以将它导出为逗号分隔文件,然后使用循环和streamreader对象来分析每个逗号分隔值数组。

有点儿四围虽然...