Link to home
Start Free TrialLog in
Avatar of fbroccoli
fbroccoli

asked on

How do I programmatically kill a MS Excel process within my C# asp.net application that created and started the process

I've written a C# asp.net application that uses Microsoft.Office.Interop.Excel.  Application creates an Excel spreadsheet, saves it and then tries to close and quite Excel but the Excel process is still running in the Task Manager.  (same code works in a console app or Windows Forms application but not in my asp.net web app).

Here is the basis of the code:

using MyExcel = Microsoft.Office.Interop.Excel;
.
.
.
MyExcel.Application xlApp;
MyExcel.Workbook xlWorkBook;
MyExcel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
.
.
 xlApp = new MyExcel.Application();
 xlWorkBook = xlApp.Workbooks.Add(misValue);
 xlApp.DisplayAlerts = false;
 xlWorkSheet = (MyExcel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
 xlWorkSheet.Name = "Daily Report";
.
.
xlWorkBook.SaveAs(myFile, MyExcel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, MyExcel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close();
xlApp.Quit();

Open in new window

Avatar of Nicolas Lecanu
Nicolas Lecanu
Flag of Guadeloupe image

Hi fbroccoli,

You need to use the function "Application.Quit" method(Excel)

Here a exemple of this function.
Avatar of fbroccoli
fbroccoli

ASKER

My code contains:  xlApp.Quit();

Is my syntax incorrect?
You are right, sorry.

Can you try this function ?

    private void KillExcel()
    {
        Process[] AllProcesses = Process.GetProcessesByName("excel");

        // check to kill the right process
        foreach ( Process ExcelProcess in AllProcesses) {
        if (myHashtable.ContainsKey(ExcelProcess.Id) == false)
         ExcelProcess.Kill(); 
        }

        AllProcesses = null;
    }

Open in new window

you can read this question which provide several options to do that:

C# Visual Studio question regarding how to kill Excel interop process.
https://www.experts-exchange.com/questions/29077256/C-Visual-Studio-question-regarding-how-to-kill-Excel-interop-process.html
Good morning Nicolas,

I have copied and pasted the function into my code.  What do I replace "MyHashtable" with so I can rebuild my application and test it?

Thank you,
Frank
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.