Saturday, July 10, 2010

How to find Process Id of Excel Opening in ASP.NET Application

Here is the Sample C# code to kill the Excel Process Opened in an ASP.NET (using Office interop Component)


Application oXLApp;
// Here your will create your Excel Sheet and do the operation

Workbook oWB = oXLApp.Workbooks.Open("C:\TestExcel.xls",Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
Sheets oSheets = oWBk.Worksheets;
Worksheet sheet = (Worksheet) oSheets.get_Item(1);

//Do all the stuff here

oWB.Close(null, null,null);
oXLApp.Workbooks.Close();
oXLApp.Quit();
oSheets = null;
sheet = null;
oWB = null;
oXLApp = null;

Marshal.ReleaseComObject(oXLApp);
Marshal.ReleaseComObject(oSheets);
Marshal.ReleaseComObject(sheet);
Marshal.ReleaseComObject(oWB);
GC.Collect();

After disposing the all object write the following code

//Include the System.Runtime.InteropServices namespace, since we have to use the DllImport Attributes

using System.Runtime.InteropServices;

//Now declare the two Method Findwindow anf GetWindowThreadProcessId as show below

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
internal static extern IntPtr FindWindow(String className, String windowName);

[DllImport("user32.dll")]
internal static extern int GetWindowThreadProcessId(IntPtr wHwnd, ref int processId);

oXLApp.Caption="TestExcel";

String strXLVer = oXLApp.Version;
String strXLCap = oXLApp.Caption;

IntPtr xlappHandle = IntPtr.Zero;

//Find the Version of Excel.
//If it is above 8 then we can get the Object Handle id directly
//Otherwise we have to use the FindWindow and Get the Handle Id using Catption
if (Convert.Toint(appVersion) >= 9)
{
xlappHandle = new IntPtr(oXLApp.Parent.Hwnd);
}
else
{
xlappHandle = FindWindow(null, strXLCap);
}

//Get the Process Id by using GetWindowThreadProcessId method and the Process Id will be the ref Parameter
int processId = 0;
GetWindowThreadProcessId(xlappHandle, ref processId);

System.Diagnostics.Process process = System.Diagnostics.Process.GetProcessById(processId);
process.Kill();

No comments: