【问题标题】:How to change the odc connection file paths in excel using c#如何使用c#更改excel中的odc连接文件路径
【发布时间】:2014-01-09 16:58:58
【问题描述】:

我有一个带有多个工作表的 excel 文件(c# 项目中的嵌入资源),这些工作表使用 odc 文件中的连接信息从 SQL Server 获取数据。我想更新 excel 文件以在我指定的特定文件夹中查找这些 odc 文件,因此需要相应地更新 excel odc 连接文件路径。如何通过 c# 执行此操作,例如,如果我将 odc 文件输出到“d:\odcFiles\abc.odc”,那么我想将 excel 连接路径更新为“d\odcFiles\abc.odc”。对于所有其他 odc 文件也是如此。任何帮助将不胜感激。

突出显示的部分是我所指的(odc 文件的位置),我想通过 c# 即时更改:

【问题讨论】:

    标签: c# sql-server excel odbc oledb


    【解决方案1】:

    一种方法,可能是最简单的方法,是直接编辑注册表。

    [更新] 我不知道 ODBC。但我已经使用此代码来动态访问 excel 文件。这是一个 asp.net 应用程序,但重要的数据库内容在那里。

    // using System.Data.OleDb
    OleDbConnection ExcelConection = null;
    OleDbCommand ExcelCommand = null;
    OleDbDataReader ExcelReader = null;
    OleDbConnectionStringBuilder OleStringBuilder = null;
    
    try
    {
        OleStringBuilder =
            new OleDbConnectionStringBuilder(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';");
        OleStringBuilder.DataSource = MapPath(@"~\App_Datav\MyExcelWorksheet.xls");
    
        ExcelConection = new OleDbConnection();
        ExcelConection.ConnectionString = OleStringBuilder.ConnectionString;
    
        ExcelCommand = new OleDbCommand();
        ExcelCommand.Connection = ExcelConection;
        ExcelCommand.CommandText = "Select * From [Sheet1$]";
    
        ExcelConection.Open();
        ExcelReader = ExcelCommand.ExecuteReader();
    
        GridView1.DataSource = ExcelReader;
        GridView1.DataBind();
    }
    catch (Exception Args)
    {
        LabelErrorMsg.Text = "Could not open Excel file: " + Args.Message;
    }
    finally
    {
        if (ExcelCommand != null)
            ExcelCommand.Dispose();
        if (ExcelReader != null)
            ExcelReader.Dispose();
        if (ExcelConection != null)
            ExcelConection.Dispose();
    }
    

    【讨论】:

    • 史蒂夫是什么意思? excel 文件是 c# 项目中的嵌入式资源,我想即时更新所有报告的路径,并将文件与 odc 文件一起输出到用户指定的文件夹。
    • "excel 文件是 c# 项目中的嵌入式资源..." 我不知道。也许您应该使用该信息更新您的问题。
    • 已更新。关于如何修改 excel 文件和更新这些 odc 文件路径的任何想法?
    • 我更新了我的答案。 ODBC 配置存储在 PC 上并且 excel 文件嵌入在您的应用程序中的事实是......有问题(以我的思维方式)。
    • 感谢史蒂夫的帮助,但我认为没有一种干净的方法可以做我想做的事情,所以我求助于创建具有特定路径的 odc 文件,然后输出odc 文件到该路径,因此 excel 文件在查看其数据连接文件路径时始终可以找到它们。
    猜你喜欢
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 2016-10-22
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    相关资源
    最近更新 更多