Note that there are some explanatory texts on larger screens.

plurals
  1. POCannot open Excel file in C#
    text
    copied!<p>I have the following C# function in my project, which is supposed to open and return an existing Excel workbook object:</p> <pre><code>Application _excelApp; // ... private Workbook OpenXL(string path, string filename) { try { if (_excelApp == null) { _excelApp = new Application(); } Workbook workBook = _excelApp.Workbooks.Open(path + filename, // Name 0, // Do not update links true); // Open read-only return workBook; } catch (Exception e) { _excelApp = null; throw new ArgumentException("Error opening " + path + filename, e); } } </code></pre> <p>But when I run it with "C:\" and "scratch.xlsx", the Open() call throws the following error:</p> <pre><code>Microsoft Excel cannot access the file 'C:\scratch.xlsx'. There are several possible reasons: • The file name or path does not exist. • The file is being used by another program. • The workbook you are trying to save has the same name as a currently open workbook. </code></pre> <p>The file and path does exist: I have copied the path from the error message and pasted it into a command window and the file loads up in Excel. The file is not locked: Excel can open it fine but my program cannot, even straight after a reboot. I am not trying to save it, I am trying to open it so the last option is irrelevant.</p> <p>I am at a loss to understand why this simple piece of code is not working. Any suggestions would be hugely appreciated.</p> <p>[edit] I have now tried opening that file from my personal network drive (M:) and from a USB stick. All to no avail.</p> <p>The application is actually a Windows service, running under the local system account and generating reports. It currently write CSV reports with no access problems whatsoever. I am now trying to get it to open an excel file as a template report and fill in various fields. It is when opening the Excel file that it fails. I am thinking that the administrator account option everyone is suggesting is a red herring since it can write CSV files wityh no problem. [/edit]</p> <p>--- Alistair.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload