Reputation: 8068
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?
Upvotes: 1
Views: 499
Reputation: 1
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 */
);
Upvotes: 0
Reputation: 29000
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)
{ }
Upvotes: 0
Reputation: 2989
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:
Hope these are helpful
Upvotes: 2