This project has moved and is read-only. For the latest updates, please go here.

Closing workbook without saving

Mar 1, 2011 at 2:49 PM

I'm currently trying to develop an application which uses ClosedXML to read an .xlsx file and use some of these values to generate a .csv file. So far it seems to work fairly well but I still have some problems which might simply be due to my lack of knowledge of how C# treats files, streams etc.

Currently I ask the user (using an OpenFileDialog) to choose the Excel file he/she wants to convert and open the Excel-file using:

originalWorkbook = new XLWorkbook(ofd.OpenFile())

Here I encounter the first problem: If the user has the file open in Excel, an IOException is thrown. Since I only need to read values from the workbook I would like to just open it as a readonly file which should be possible, even if the user has the file opened in Excel.

My second problem is that the application seems to keep the workbook open until I close the application. This means that the user will only be able to open the file in Excel as a readonly file until the application is closed. Since I only want to read data from the workbook I'm not interested in saving it at any point. Is there a way to close the workbook without using "SaveAs"?

Mar 1, 2011 at 5:13 PM

1st Problem: ClosedXML uses MS Open XML SDK which needs a lock on files before opening them. One solution would be for you to copy the file before opening it (since it's going to be a read-only operation anyway).

2nd Problem: ClosedXML only touches the file on opening and closing. Once you instantiate the XLWorkbook with your file, the file is no longer under a lock. If you don't want to save your changes then just don't call the .SaveAs method. It's all managed code so you can just quit your program and your changes will be lost.

Mar 2, 2011 at 9:18 AM

1st problem: I guess I can just make some kind of temporary copy to open and delete after use. I just wondered if there was some way to open the file as readonly.

2nd problem: This is how I understood the code to work as well but somehow I keep getting notified that the file is used by another application if I try to open it in Excel after having opened it in my application. This message keeps appearing until I close the instance of my application where I had previously used the file. However, I guess if I do create a temporary file and use that to read from this will not really be a problem that matters.

Mar 2, 2011 at 4:25 PM
Edited Mar 2, 2011 at 4:25 PM

1) Just to clarify, the files are open as read-only but it needs a lock on the file to read it (even if no changes are going to be made). This is the way the Open XML SDK works.

2) Try the following:


        static void Main(string[] args)
            var wb = new XLWorkbook(@"AnyExcelFile.xlsx");
            Console.WriteLine("Try to open the file with Excel and press any key to end.");