2009-06-22 45 views
0

我使用VSTS 2008 + C#+ .Net 3.5讀取由Excel 2007創建的Excel文件(但保存爲Excel 2003 xls格式)。這是我的代碼,執行代碼adapter.Fill(城市)時,出現異常 - 「OldDbException無法找到可安裝的ISAM」。任何想法有什麼不對?我的代碼讀取Excel文件錯誤

static void Main(string[] args) 
{ 
    string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\temp\data.xls;ExtendedProperties=""Excel 8.0;HDR=YES;"""; 

    DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb"); 

    DbDataAdapter adapter = factory.CreateDataAdapter(); 

    DbCommand selectCommand = factory.CreateCommand(); 
    selectCommand.CommandText = "SELECT ID FROM [Sheet1$]"; 

    DbConnection connection = factory.CreateConnection(); 
    connection.ConnectionString = connectionString; 

    selectCommand.Connection = connection; 

    adapter.SelectCommand = selectCommand; 

    DataSet cities = new DataSet(); 

    adapter.Fill(cities); // OldDbException Could not find installable ISAM 

    return; 
} 

由於事先 喬治

回答

2

我複製你的問題,用替換你的代碼下面,它應該工作

static void Main (string [] args) 
    { 
     string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\temp\Data.xls;Extended Properties=""Excel 8.0;HDR=YES;"""; 
     DbProviderFactory factory = DbProviderFactories.GetFactory ("System.Data.OleDb"); 

     using (DbConnection connection = factory.CreateConnection ()) 
     { 
      connection.ConnectionString = connectionString; 

      using (DbCommand command = connection.CreateCommand ()) 
      { 
       // Cities$ comes from the name of the worksheet 
       command.CommandText = "SELECT ID FROM [Sheet1$]"; 

       connection.Open (); 

       using (DbDataReader dr = command.ExecuteReader ()) 
       { 
        DataSet cities = new DataSet (); 
        cities.Load (dr, LoadOption.OverwriteChanges, new [] { "Sheet1" }); 
       } 
      } 
     } 

     return; 
    } 
+0

「你有ADO安裝在機器上運行此代碼?」 - 如何檢查?我安裝了完整的VSTS 2008,只是假設一切都在那裏...... :-) – George2 2009-06-22 18:20:02

+1

看到我的編輯,據我所知VS不會安裝MDAC組件 – 2009-06-22 18:32:15

+0

您的代碼工作,很酷! – George2 2009-06-22 18:53:12