javacoder123
javacoder123

Reputation: 193

Close excel workbook without killing the excel process or other workbooks - C#

I want to be able to end a task called "Microsoft Excel - test.xlsx" without ending any other applications that are also Excel applications.

I have used

foreach (Process process in Process.GetProcesses())
            {
                if (process.ProcessName.Equals("EXCEL"))
                    process.Kill();
            }

but this kills all other Excel workbooks that are open. Is it possible to only kill or end the specified workbook?

Upvotes: 0

Views: 3001

Answers (1)

javacoder123
javacoder123

Reputation: 193

My solution finds the workbook and then closes it.

/// <summary>
    /// Gets the current Excel process and specified workbook and closes it.
    /// If the workbook was the only one in the application, it then closes excel as well.
    /// </summary>
    public static void CloseWorkbook()
    {
        try
        {
            Application excelApplicationProcess = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); // get current excel process

            foreach (object wb in excelApplicationProcess.Workbooks)
            {
                if (((Workbook)wb).FullName.Equals(Settings.Default.Test))
                    ((Workbook)wb).Close(false, Settings.Default.Test, Missing.Value);
            }

            if (excelApplicationProcess.Workbooks.Count == 0) // if it was the only one close excel as well
                excelApplicationProcess.Quit();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

Upvotes: 1

Related Questions