我有一个excel文件(c#项目中的嵌入式资源),其中包含多个工作表,这些工作表使用odc文件中的连接信息从SQL Server获取数据。我想更新excel文件以在我指定的特定文件夹中查找这些odc文件,因此需要相应地更新excel odc连接文件路径。我怎么能通过c#这样做,所以例如,如果我将odc文件输出到“d:\ odcFiles \ abc.odc”,那么我想将excel连接路径更新为“d \ odcFiles \ abc.odc”。同样适用于所有其他odc文件。非常感谢任何帮助。
突出显示的部分是我所指的(odc文件的位置),我想通过c#动态更改:
答案 0 :(得分: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();
}