简体   繁体   中英

Can't open bound excel file in C# project

I have an excel file in my project which is listed as resource.

Now I try to open it with a button click like this:

private void Button_Click_Blist(object sender, RoutedEventArgs e)
{
    Excel.Application xl = new Excel.Application();
    Excel.Workbook wb = xl.Workbooks.Open("Blist.xlsx");
}

My problem is that it says that it can't find the file and throws this exception:

System.Runtime.InteropServices.COMException

We couldn't find 'Blist.xlsx'. Was the object perhaps moved, renamed, or deleted?

This code uses OLE Automation to start Excel and tell it to open a file in the relative path Blist.xlsx . The executable in this case is Excel , not your own application. The relative path will be resolved using Excel's working directory.

To avoid this problem, pass the absolute file path to Excel :

var fullPath=Path.GetFullPath("Blist.xlsx");
Excel.Workbook wb = xl.Workbooks.Open(fullPath);

Another possibility, which gives no control of (or dependency on) Excel, is to just "start" the file with Process.Start , eg :

Process.Start("Blist.xlsx");

Or

var fullPath=Path.GetFullPath("Blist.xlsx");
Process.Start(fullPath);

The Windows Shell will find the application that can open this document based on its extension and start it, passing the file path as an argument. This can start Excel, Libre Calc or any other application registered to open this particular file extension.

So I tried this and apparently the .Open() method some extra complexety with relative paths (see @PanagiotisKanavos comment). You can make a work around, by getting the current directory path, and pre-pending it, giving the absolute path of the file:

string filename = "Blist.xlsx";
string currentPath = Directory.GetCurrentDirectory();

var xl = new Microsoft.Office.Interop.Excel.Application();            
var wb = xl.Workbooks.Open(currentPath + "\\" + filename);

xl.Visible = true;

However, you should (almost) never use hardcoded file names in your code. So the above solution is just an example, not something to copy into production code...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM