2010-03-09 415 views

回答

7

試試下面的C#代碼:

Dim MyCommand As System.Data.OleDb.OleDbDataAdapter 
Dim MyConnection As System.Data.OleDb.OleDbConnection 
MyConnection = New System.Data.OleDb.OleDbConnection(_ 
"provider=Microsoft.Jet.OLEDB.4.0; " & _ 
"data source=" & ExcelFilePath & "; " & _ 
"Extended Properties=Excel 8.0") 

' Select the data from Sheet1 ([in-house$]) of the workbook. 
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [in-house$]", MyConnection) 

DS = New System.Data.DataSet 
MyCommand.Fill(DS) 
Dt = DS.Tables(0) 
DataGrid1.DataSource = Dt 

對於特定的細胞試試這個(它會讀取小區D6)。需要注意的是它不使用OLEDB連接,而是直接訪問。

命名空間要求使用Microsoft.Office.Core;

通過添加COM引用添加它來的Microsoft Office 12.0對象庫

Dim oApp As New Excel.Application 
Dim oWBa As Excel.Workbook = oApp.Workbooks.Open("c:\Test.XLS") 
Dim oWS As Excel.Worksheet = DirectCast(oWBa.Worksheets(1), 
Excel.Worksheet) 
oApp.Visible = False 

Dim oRng As Excel.Range 
oRng = oWS.Range("D6") 
MsgBox(oRng.Value) 
+0

是它的讀取所有的Excel文件。我如何讀取特定的單元格(即:我的意思是如何在Excel表格中讀取A11?)?您的代碼集用於讀取整個文件。謝謝。 – RedsDevils 2010-03-09 07:59:34

+0

導入使用Excel.Application需要什麼? – RedsDevils 2010-03-09 08:20:40

+0

好吧,我得到它參考COM。謝謝,我會嘗試你的代碼。 – RedsDevils 2010-03-09 08:32:22

0

是.NET,你可以用它來獲得公式,值的Excel兼容的電子表格組件,格式化文本,等等......任何單元格。下面是一個簡單的例子:

using System; 
using SpreadsheetGear; 

namespace Program 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // Load a workbook from disk and get the first worksheet. 
      IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(@"C:\tmp\HelloWorld.xlsx"); 
      IWorksheet worksheet = workbook.Worksheets[0]; 
      // Get a reference to cell A1 and write the formatted value to the console. 
      IRange a1 = worksheet.Cells["A1"]; 
      Console.WriteLine("A1={0}", a1.Text); 
      // Get a reference to B2 and write the formula/value/text to the console. 
      IRange b2 = worksheet.Cells[1, 1]; 
      Console.WriteLine("B2 Formula={0}, Value={1}, Text={2}", b2.Formula, b2.Value, b2.Text); 
     } 
    } 
} 

你可以看到現場的樣品here或者,如果你想嘗試一下自己下載免費試用here

聲明:我自己的SpreadsheetGear LLC

0

試試這個C#代碼,

DimobjEXCELCon As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=EXCLE_FILE_PATH;Extended Properties=""Excel 12.0 Xml;HDR=Yes""") 
ExcelConnection.Open() 

Dim objQuery As String = "SELECT * FROM [Sheet1$]" 'get values from sheet1, here you can change your sheet name 

Dim objCMD As OleDbCommand = New OleDbCommand(objQuery,objEXCELCon) 
Dim objDR As OleDbDataReader 

Dim SQLconn As New SqlConnection() 
Dim szCON As String = "Connection string for database" 
SQLconn.ConnectionString = szCON 
SQLconn.Open() 


Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLConn) 
bulkCopy.DestinationTableName = "TableToWriteToInSQLSERVER" 

Try 
    objDR = objCMD.ExecuteReader 
    bulCopy.WriteToServer(objDR) 
    objDR.Close() 
    SQLConn.Close() 

Catch ex As Exception 
    MsgBox(ex.ToString) 
End Try