2011-04-09 105 views
0

我正在使用c#.net中的Windows應用程序,我需要通過使用c#中的代碼將Excel表導入Access數據庫。我發現在網絡上下面的代碼,並試圖使用:從Excel導入數據通過c#.net訪問數據庫

string path = @"D:\project_excel"; 
     OleDbConnection con; 
     System.Data.DataTable dt = null; 
     //Connection string for oledb 
     string conn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + "; Extended Properties=Excel 8.0;"; 
     con = new OleDbConnection(conn); 
     try 
     { 
      con.Open(); 

      dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 
      String[] excelsheets = new String[dt.Rows.Count]; 
      int i = 0; 

      foreach (DataRow dr in dt.Rows) 
      { 
       excelsheets[i] = dr["TABLE_NAME"].ToString(); 
       i++; 
      } 
      // here i manaually give the sheet number in the string array 
      DataSet ds = new DataSet(); 
      foreach (string temp in excelsheets) 
      { 
       // Query to get the data for the excel sheet 
       //temp is the sheet name 
       string query = "select * from [" + temp + "]"; 
       OleDbDataAdapter adp = new OleDbDataAdapter(query, con); 
       adp.Fill(ds, temp);//fill the excel sheet data into a dataset ds 
      } 

     } 
     catch (Exception ex) 
     { 

     } 
     finally 
     { 
      con.Close(); 
     } 

但是它給出了下面提及的異常:

Microsoft Jet數據庫引擎無法打開文件「d:\ project_excel 」。它已經由另一個用戶專門打開,或者您需要查看其數據的權限。

此外我不知道擴展屬性的含義。我正在使用Microsoft Office 2007軟件包。如果我將擴展屬性設置爲7.0,則會出現以下錯誤:

找不到可安裝的ISAM。

請幫忙提供一些代碼示例。

在此先感謝..

+0

在運行代碼時,文件是否在Excel中打開? – Oded 2011-04-09 19:45:49

回答

0

檢查是否連接字符串爲您的Access數據庫的版本是正確的。

詳情,請訪問ConnectionString.com

通過

穆罕默德Inshafudeen J.

0

對於錯誤:找不到可安裝ISAM。

1:Excel文件保存爲 「Excel中97-2003 wrokbook」 2:還包括參考 「的Microsoft.Office.Interop.Excel」

好運!