【问题标题】:Connection string in app.configapp.config 中的连接字符串
【发布时间】:2015-05-01 22:12:59
【问题描述】:

如何在 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""";

【问题讨论】:

  • 这个问题提供了一个将其添加到 app.config 的示例。
  • 我重新编辑了我的问题。
  • 我相信它保持不变,只是 connectionString 属性包含 Excel 文件。看起来您已经有了一个有效的连接字符串。链接的问题更多地展示了如何处理提供者的详细信息。
  • 您可以将连接字符串的每个部分存储为单独的密钥,并从程序中的这些参数构建一个字符串(连接字符串)。

标签: c# excel


【解决方案1】:

在网络配置文件中试试这个-

<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>

【讨论】:

  • 错误是{“未在 ConnectionString 中指定 OLE DB 提供程序。例如,'Provider=SQLOLEDB;'。”}
【解决方案2】:

我自己解决了这个问题。

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;



    }

【讨论】:

    【解决方案3】:

    通常他们自己坐在一个部分:

      <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 是什么或使用什么名称,以便提供程序找到正确的连接字符串。

    【讨论】:

    • 我认为那是提供者名称,但不确定,因为我没有通过 ACE OLE 访问 excel
    • 我收到错误,因为“{”连接字符串中未指定 OLE DB 提供程序。例如,'Provider=SQLOLEDB;'。"}"
    猜你喜欢
    • 2013-02-01
    • 2023-04-04
    • 2015-09-16
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 2018-01-06
    • 2023-04-04
    相关资源
    最近更新 更多