Search code examples
spreadsheetgear

spreadsheetgear - open/save file


I want to update an existing Excel file using SpreadsheetGear.

I load the Excel file using:

 _activeWorkbook = Factory.GetWorkbook(@"./excel/test.xls");
 workbookView1.ActiveWorkbook = _activeWorkbook;

but when I want to save it:

    private void menuSave_Click(object sender, EventArgs e)
    {
        workbookView1.GetLock();

        try
        { 
            _activeWorkbook.Save();
        }
        finally
        {
            workbookView1.ReleaseLock();
        }
    }

I get this error: System.IO.IOException: The process cannot access the file 'C:...\bin\Debug\excel\test.xls' because it is being used by another process.


Solution

  • As the exception indicates, some other process (or possibly your same application, if you utilize multiple threads) has a lock on your file and so SpreadsheetGear cannot save it back to disk. Any number of other external processes could be the culprit, such as anti-virus software scanning your file or having it open in Excel itself when you try to save it. There is no way to determine the exact cause with just the information provided above.

    What I can tell you is that SpreadsheetGear does not keep any file streams open after reading and writing files. The file stream and lock on the file is only open for as long as it takes to read/write its contents, which is usually very short if the file is small. Put another way, @".excel/test.xls" should be writable immediately after your Factory.GetWorkbook(...) line executes.