2015-04-30 96 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; 



    } 
相关问题