OleDbConnection() opens an Excel file in any open Excel window. But does not if there isnt a window open

亡梦爱人 提交于 2020-01-14 08:41:08

问题


I am writing an application which uses an OleDbAdapter to access information in an Excel file. When I try to create a connection to the Excel file if the user has another (unrelated) Excel file open on their desktop then the file being connected to by the adapter opens in this window in Read-Only format. If the user does not have an instance of Excel open then the files stay hidden.

Here is my code:

foreach (item app in apps)

{   

   DataTable dt = new DataTable();

   string CnStr = ("Provider=Microsoft.Jet.OLEDB.4.0;" + ("Data Source="
                  + ((app.FilePath) + (";" + "Extended Properties=\"Excel 8.0;\""))));

   string OleDbString = ("Select * from [" + app.SheetName + "$]");                              

   OleDbDataAdapter Adapter = new OleDbDataAdapter();

   var conn = new OleDbConnection(CnStr);
   conn.Open(); <----------------------------This is where the files are being opened.

   var cmd = new OleDbCommand(OleDbString, conn);

   Adapter.SelectCommand = cmd;


   Adapter.Fill(app.DataTable);

   conn.Close();

   Adapter.Dispose();

}

Does anybody know why the OleDbConnection() would open a file if an instance of Excel was open but would not if one was not?


回答1:


You should post the code to initialize your apps variable. Most probably the answer to your question lies in there. Does it use a GetObject or CreateObject method?



来源:https://stackoverflow.com/questions/8229929/oledbconnection-opens-an-excel-file-in-any-open-excel-window-but-does-not-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!