2015-04-30 95 views
0

如何在Windows窗體應用程序的app.config文件中添加此C#代碼連接字符串? 我看到添加訪問數據庫的例子,但我需要添加Excel文件數據,所以無法找到以前的問題在Excel文件連接在app.config。app.config中的連接字符串

OleDbConnection conn = new OleDbConnection(); 
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MISD_report.xlsx" + @";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0"""; 
+0

這個問題特點加入它的app.config的例子。 –

+0

我重新編輯了我的問題。 – Cookie

+0

我相信它保持不變,只是'connectionString'屬性包含Excel文件。看起來你已經有了一個有效的連接字符串。鏈接的問題更多地展示瞭如何處理提供者細節。 –

回答

0

試試這個在Web配置文件 -

<connectionStrings> 
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties='Excel 8.0'" /> 
<add name="ConnStrName" connectionString="Data Source=database;Initial Catalog=database-name;Persist Security Info=True;User ID=your username;Password=your password" /> 
</connectionStrings> 
+0

錯誤是{「在ConnectionString中沒有指定OLE DB提供程序,例如'Provider = SQLOLEDB;'。} – Cookie

0

通常他們在一節坐在自己:

<connectionStrings> 
    <add name="myConnectionName" providerName="myProvider" connectionString="Data Source=D:\MISD_report.xlsx;Extended Properties=Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0" /> 
    </connectionStrings> 

我不知道什麼OLE/Excel中的providerName還是什麼名稱中使用這樣的供應商找到正確的連接字符串。

+0

提供提供者名稱時不起作用。 – Cookie

+2

Cookie

+0

我認爲是提供者名稱,但不知道,因爲我沒有通過ACE OLE訪問Excel –

0

我這個解決我自己。

的app.config設置:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 

    <connectionStrings> 
    <add name="MSIDConn" 
     connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MISD_report.xlsx;Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0'" 
      providerName="System.Data.OleDb" /> 

    </connectionStrings> 
</configuration> 

加入這些2線在Form1.cs

使用System.Data.OleDb; using System.Configuration;

在按鈕單擊事件:

private void button1_Click(object sender, EventArgs e) 
    { 

     string excelconn = ConfigurationManager.ConnectionStrings["MSIDConn"].ConnectionString; 
      OleDbConnection conn = new OleDbConnection(); 
      conn.ConnectionString = excelconn; 

     OleDbCommand command9 = new OleDbCommand 
     (
      "SELECT P1, P2, P3 " + 
       " FROM [PE_Actual$] ", conn 
     ); 
     DataSet ds9 = new DataSet(); 
     OleDbDataAdapter adaptor9 = new OleDbDataAdapter(command9); 
     adaptor9.Fill(ds9, "testtable"); 
     dataGridView1.DataSource = ds9.Tables[0].DefaultView; 



    } 
相關問題