2011-08-30 252 views
3

我有一個連接字符串來讀取我的C#項目,看起來像這樣一個Excel文件..讀取Excel文件從C#

String ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + 
             "Data Source=" + VariableFile + ";" + 
             "Extended Properties=Excel 8.0;"; 

我也有objConn.Open();打開文件..

問題是我的程序打開文件的唯一時間是如果我手動打開Excel文件並運行我的程序。任何人都可以幫助我從我的C#代碼打開文件,而不必手動打開它。我收到錯誤消息:當我嘗試運行它時未找到可安裝的ISAM,而無需首先打開Excel文件。

謝謝

回答

6

我覺得您的連接字符串格式錯誤的,「找不到可安裝ISAM」通常是這樣的指示。

試試這個,它是由一塊的業務代碼,我有:

Excel 2007中

string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=No;IMEX=1\";", fullPath); 

Excel 2003中

string connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\";", fullPath); 
+0

我認爲這是使用Excel 8.0屬性沿OLEDB.12.0 ..我從來沒有見過這個,通常使用Jet.OLEDB.4.0與Excel 8.0 OR ACE.OLEDB.12.0 with Excel 12.0 – crlanglois

+0

謝謝!修復了它 – Juan

0

有用於連接到Excel不同的供應商。也許你應該嘗試使用不同的。 看一看這裏的例子:

http://www.connectionstrings.com/excel

提供商爲Excel »的Microsoft Jet OLE DB 4.0 »ACE OLEDB 12.0 ».NET Framework數據提供OLE DB(的OleDbConnection) »Microsoft Excel中ODBC驅動程序 ».NET Framework數據提供程序的ODBC(OdbcConnection) ».NET xlReader爲Microsoft Excel(ExcelConnection)

在你的情況,你應該有這樣的事情: Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\ myFolder \ myOldExcelFile.xls;擴展屬性=「Excel 12.0; HDR = YES」;

2

下面的代碼將讀取Excel文件&填充數據表,其數據

try 
      { 
       string connectionString = string.Empty; 

       if (Path.GetExtension(ExcelFileName) == ".xlsx") 
       { 
        connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFileName + 
         ";Extended Properties=Excel 12.0;"; 
       } 
       else 
       { 
        connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFileName + ";Extended Properties=Excel 8.0;"; 
       } 

       OleDbCommand selectCommand = new OleDbCommand(); 
       OleDbConnection connection = new OleDbConnection(); 
       OleDbDataAdapter adapter = new OleDbDataAdapter(); 
       connection.ConnectionString = connectionString; 

       if (connection.State != ConnectionState.Open) 
        connection.Open(); 

       DataTable dtSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 

       List<string> SheetsName = GetSheetsName(dtSchema); 
       for (int i = 0; i < SheetsName.Count; i++) 
       { 
        selectCommand.CommandText = "SELECT * FROM [" + SheetsName[i] + "]"; 
        selectCommand.Connection = connection; 
        adapter.SelectCommand = selectCommand; 
        DataTable Sheet = new DataTable(); 
        Sheet.TableName = SheetsName[i].Replace("$", "").Replace("'", ""); 
        adapter.Fill(Sheet); 

        if (Sheet.Rows.Count > 0) 
        { 
         Records.Tables.Add(Sheet);       
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       WriteLog(ex); 
      } 
+0

您沒有包含GetSheetsName函數 – lunarquaker

1

我最近不得不使用此提供一個Azure的網絡招聘地方,我需要使用一個OLEDB提供者而不是Excel。

您可以使用以下設置安裝Microsoft.ACE.OLEDB.12.0提供程序。

Microsoft Access數據庫引擎2010可再發行 https://www.microsoft.com/en-us/download/details.aspx?id=13255

一旦安裝,你可以修改.xls和.xlsx文件擴展名的連接字符串。

例如,下面的代碼將Excel文件轉換成一個數據集與在Excel文件每個工作表的DataTable。

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Configuration; 
using System.Data; 
using System.Data.OleDb; 
using System.Linq; 
using System.Net; 

...

public DataSet ExcelToDataSet(string excelFilename) 
{ 
    var dataSet = new DataSet(excelFilename); 

    // Setup Connection string based on which excel file format we are using 
    var excelType = "Excel 8.0"; 
    if (excelFilename.Contains(".xlsx")) 
    { 
     excelType = "Excel 12.0 XML"; 
    } 

    // <add key="Microsoft.ACE.OLEDB" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='{1};HDR=YES;READONLY=TRUE'"/> 
    var connectionStringFormat = ConfigurationManager.AppSettings["Microsoft.ACE.OLEDB"].ToString(); 
    var excelNamePath = string.Format(@"{0}\{1}", Environment.CurrentDirectory, excelFilename); 
    var connectionString = string.Format(connectionStringFormat, excelNamePath, excelType); 

    // Create a connection to the excel file 
    using (var oleDbConnection = new OleDbConnection(connectionString)) 
    { 
     // Get the excel's sheet names 
     oleDbConnection.Open(); 
     var schemaDataTable = (DataTable)oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 
     oleDbConnection.Close(); 
     var sheetsName = GetSheetsName(schemaDataTable); 

     // For each sheet name 
     OleDbCommand selectCommand = null; 
     for (var i = 0; i < sheetsName.Count; i++) 
     { 
      // Setup select command 
      selectCommand = new OleDbCommand(); 
      selectCommand.CommandText = "SELECT * FROM [" + sheetsName[i] + "]"; 
      selectCommand.Connection = oleDbConnection; 

      // Get the data from the sheet 
      oleDbConnection.Open(); 
      using (var oleDbDataReader = selectCommand.ExecuteReader(CommandBehavior.CloseConnection)) 
      { 
       // Convert data to DataTable 
       var dataTable = new DataTable(sheetsName[i].Replace("$", "").Replace("'", "")); 
       dataTable.Load(oleDbDataReader); 

       // Add to Dataset 
       dataSet.Tables.Add(dataTable); 
      } 
     } 

     return dataSet; 
    } 
} 

private List<string> GetSheetsName(DataTable schemaDataTable) 
{ 
    var sheets = new List<string>(); 
    foreach(var dataRow in schemaDataTable.AsEnumerable()) 
    { 
     sheets.Add(dataRow.ItemArray[2].ToString()); 
    } 

    return sheets; 
}