2009-09-23 114 views
0

這是訪問MS Office Excel 2007文件的正確方法嗎?C#訪問Excel工作表

 String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + 
    "Data Source=" + file_path + ";Extended Properties=Excel 8.0;"; 

如果是這樣,我該如何訪問某個工作表並插入行?鏈接也歡迎。

回答

1

連接字符串

connectionString = @"provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + @";Extended Properties=""Excel 12.0;HDR=YES;IMEX=1"""; 

讀取數據

excelConnection = new System.Data.OleDb.OleDbConnection(connectionString); 
     excelConnection.Open(); 
     dbSchema = excelConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null); 
     firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString(); 
     strSQL = "SELECT * FROM [" + firstSheetName + "]"; 
     da = new OleDbDataAdapter(strSQL, excelConnection); 
     da.Fill(dt); 

寫入數據看Excel Generation這款採用自動化雖然。它可能有幫助。

1

您可以使用Excel Interop(的Microsoft.Office.Interop.Excel):

這裏是一些代碼片段:

object missing = (object) Type.Missing; 

Application app = new Application(); 

Workbooks books = app.Workbooks; 

Workbook book = books.Open("somefile.xls", missing, missing, missing, missing, missing, missing, 
      missing, missing, missing, missing, missing, missing, missing, missing); 

Worksheet sheet = (Worksheet)book.Worksheets[1]; 

它有一些weirdnesses(像那些 「失蹤」 的參數),但它工作非常順利。如果採取這種方法,請注意EXCEL.exe進程不會成爲孤兒。