In my application I want to be able to open an excel file that already exists, and add information to this file. I use the Microsoft Interop libraries. I have noticed that if you create a new spreadsheet using Add and then Saveas you can set the file to be in exclusive mode until you close the excel application.
However I haven't found a way to do the same when Opening an existing file. The reason I want to do that is because, if I open the excel file while my application is open, then I get an exception. I presume that when I am opening the excel file using excel, it is automatically opened in exclusive mode.
I though of opening the file and then using saveas, but it didn't work.
private object missing=Type.Missing;
workbook = workbooks.Open(excelfilename,missing, false, missing, missing, missing,missing,missing,missing,missing,false, missing,missing, missing, missing);
workbook.SaveAs((String)excelfilename, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, Excel.XlSaveConflictResolution.xlLocalSessionChanges, missing, missing, missing, missing);
I am getting the exception later in the code:
Excel.Range testrange = sheet.get_Range(rangetext);
The exception I am getting is a COMException, "Exception from HRESULT: 0x800401A8".
Look at the Workbook class ExclusiveAccess property: http://msdn.microsoft.com/en-US/library/microsoft.office.tools.excel.workbook.exclusiveaccess(v=vs.80).aspx
You could go to this article for complete example of how to open an excel file/ add new sheet/ get range & set properties using Microsoft interop library
User contributions licensed under CC BY-SA 3.0