如何在app.config文件中为Windows窗体应用程序添加此C#代码连接字符串? 我看到添加访问数据库的示例,但我需要添加Excel文件数据,因此无法在app.config中找到有关Excel文件连接的上一个问题。
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 :(得分: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是什么或者使用什么名称,因此提供程序找到正确的连接字符串。
答案 1 :(得分:0)
在网络配置文件中尝试此操作 -
<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>
答案 2 :(得分: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>
在Form1.cs中添加了这两行
使用System.Data.OleDb; 使用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;
}