How can I open an Excel file without locking it?

By | February 27, 2018
Questions:

I have a process that builds an Excel report, then opens it for the user. The problem is if someone leaves the file open, it stays locked and nobody else can build the report until the first person exits the excel file.

Is there a way to open an Excel file without locking it, using either Process.Start or Microsoft’s Interop.Excel library?

I use the Interop library to build the file each time the report is run, and save it as a static file name in a shared network folder where this application is run from

using Excel = Microsoft.Office.Interop.Excel;

...

xlsBook.SaveAs(newFileName, Excel.XlFileFormat.xlWorkbookNormal);

And open the file using Process.Start

Process.Start(newFileName);
Answers:

You can try to open the file in read-only mode:

var app = new Microsoft.Office.Interop.Excel.Application();
var workbook = app.Workbooks.Open(filename, ReadOnly: true);

Or you can try to save it in shared mode:

workbook.SaveAs(filename, AccessMode: XlSaveAsAccessMode.xlShared);

Questions:
Answers:

If the end user only has to read the file instead of also modifying it, you could create a shadow copy and then open that copy.

Simply copy the original file to a temporary location and open it from there. The original file remains untouched and can thus be opened by others.

Leave a Reply

Your email address will not be published. Required fields are marked *