Excel: can only open file if using absolute path,

2020-03-18 07:43发布

I have some trouble to understande why I´m getting an exception. I have something like this:

string path = "file.xls";
if (File.Exists(path))
{
  Excel.Application xlApp = new Excel.Application();
  Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path); //exception
  //...
}

Exception:

Unhandled Exception: System.Runtime.InteropServices.COMException: 'file.xls' could not be found

Well that´s why I´m checking with File.Exists, so I dont get this exception. So how does this work, File.Exists is true, but the file still cannot be found? If I´m using an absolute path, then it´s working. Why? I would like to use this without the absolute path, any ideas? Thank you

Edit: of course the file.xls is in the same folder as my .exe -> that´s why (as expected) File.Exists is returning true. Just wanted to make this clear ;)

标签: c# .net excel file
4条回答
该账号已被封号
2楼-- · 2020-03-18 08:23

This happens because there are two processes involved, each of which has their own Current Working Directory (CWD).

Your process (the one calling File.Exists()) has a CWD which happens to hold the file that you're using. Excel has a different CWD (probably the location of the Excel executable) which of course doesn't hold the file.

You can fix this by using:

path = System.IO.Path.GetFullPath(path);

before passing path to Workbooks.open(path)

It might be possible to change Excel's CWD by calling a macro using ExecuteExcel4Macro.

See here for some details: Set Current Directory in Excel.Application via .NET Office PIA

查看更多
何必那么认真
3楼-- · 2020-03-18 08:37

This is because Excel is another process than your .exe and the filename parameter in Workbook.Open has slightly different behavior than the filename parameter in File.Exists.

When you call File.Exists, the filename parameter may be either absolute or relative. If you use relative, it is relative to your .exe, so it will find the file placed in your .exe's folder.

When you create an Excel.Application object you get a new process with a separate working directory from your .exe. Note also that when you pass a relative filename path to the Workbook.Open function, it will not look for the file in Excel's working directory, but will instead use the default document folder for Office (typically "My Documents").

So, you should always use the absolute path in this scenario.

查看更多
你好瞎i
4楼-- · 2020-03-18 08:40

i think it is because xlApp.Workbooks.Open function only knows the absolute path,not likes File.Exists function

查看更多
家丑人穷心不美
5楼-- · 2020-03-18 08:42

I found Matthew Watson's answer very helpful. It's also useful to set a relative path for Workbooks.Add() method. Here is my code for reference:

Excel.Application xlApp = new Excel.Application();

string path = "TestTemplete.xltx";
path = System.IO.Path.GetFullPath(path);
Workbook wb = xlApp.Workbooks.Add(path);
查看更多
登录 后发表回答