1

I have an issue when working with Excel from C# using the Microsoft.Office.Interop.Excel object.

The problem comes when I try and open a file to write to that I have already have open in Excel. This ultimately errors and then leaves an instance of Excel running in the background.

How can I tell that the file is already open before opening it?

Also what is the convention for disposing with the Excel objects and therefore killing the Excel process?

Dunc
  • 7,688
  • 10
  • 31
  • 38

3 Answers3

2

The following article provides a good way of checking if a file is open already:

Is there a way to check if a file is in use?

This article talks about killing the excel process:

Kill Process Excel C#

Hope these are helpful

Community
  • 1
  • 1
Gaz Winter
  • 2,924
  • 2
  • 25
  • 47
0

Hello you must to dispose your excel objects at end of treatment (workbook, applicationClass, usedRange, worksheet)

        workbook.Close(false, workbookPath, null);
        applicationClass.Quit();

        while (Marshal.ReleaseComObject(usedRange) > 0)
        { }
        while (Marshal.ReleaseComObject(worksheet) > 0)
        { }
        while (Marshal.ReleaseComObject(workbook) > 0)
        { }
        while (Marshal.ReleaseComObject(applicationClass) > 0)
        { }
Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51
0

For opening of already opened - for more just type Workbooks.Open on the MSDN. Here is the save sample, you just overwrite (an still opened) without querying :o), xlShared and xlLocalSessionChanges are keywords.

            _xlsWorkbook.SaveAs(
                 targetFileName                                                     /* Filename */
                ,Excel_ForMissing.XlFileFormat.xlExcel8                             /* FileFormat */
                ,Missing.Value                                                      /* Password */
                ,Missing.Value                                                      /* WriteResPassword */
                ,Missing.Value                                                      /* ReadOnlyRecommended */
                ,Missing.Value                                                      /* CreateBackup */
                ,Excel_ForMissing.XlSaveAsAccessMode.xlShared                       /* AccessMode */
                ,Excel_ForMissing.XlSaveConflictResolution.xlLocalSessionChanges    /* ConflictResolution */
                ,false                                                       /* AddToMru */
                ,Missing.Value                                                       /* TextCodepage */
                ,Missing.Value                                                       /* TextVisualLayout */
                ,true                                                       /* Local */
            );
Josef
  • 1
  • 1