I have the following C # function in my project, which should open and return an existing Excel workbook object:
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); } }
But when I run it with "C: \" and "scratch.xlsx", calling Open () causes the following error:
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.
The file and path exist: I copied the path from the error message and pasted it into the command window, and the file was uploaded to Excel. The file is not locked: Excel can open it, but my program cannot, even immediately after a reboot. I am not trying to save it, I am trying to open it, so the last option does not matter.
I do not understand why this simple piece of code does not work. Any suggestions would be greatly appreciated.
[edit] Now I tried to open this file from my personal network drive (M :) and from a USB drive. All to no avail.
The application is actually a Windows service running under the local system account and generating reports. He is currently writing CSV reports without any access issues. Now I am trying to open an excel file as a template report and fill in various fields. This is when an Excel file opens, which it fails. I think that the administrator account option that everyone offers is a red herring, as it can write CSV files without any problems. [/ Edit]
--- Alistair.
c # excel-interop
user41013
source share