2009-06-12 68 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對象來分析每個逗號分隔值數組。

有點兒四圍雖然...