I am working on a WPF application that uses Excel quite heavily for reporting. It takes too much time to open a new Excel app whenever I need Excel app instance to generate a new report.
Why not to keep one Excel app instance open as a singleton just for my app? And to quit this Excel singleton when my application closes? There is only a small risk that the Excel app instance stays open, I think. Or is there any hidden threat in doing this?
My code:
private static Microsoft.Office.Interop.Excel.Application _ExcelApp = null;
public static Microsoft.Office.Interop.Excel.Application ExcelApp
{
get { return _ExcelApp; }
private set { _ExcelApp = value; }
}
public static void QuitExcel()
{
if (ExcelReports.ExcelApp != null)
{
ExcelReports.ExcelApp.Quit();
ExcelReports.ExcelApp = null;
}
}
public static void StartExcel()
{
try
{
ExcelReports.ExcelApp = new Microsoft.Office.Interop.Excel.Application();
}
catch (System.Runtime.InteropServices.COMException ex)
{
throw new ApplicationException(String.Format("Cannot start Excel.\n\r{0}", ex.Message));
}
}
EDIT It seems to be working quite ok and faster, though it is certainly not the very best practice. There seems to be no way to find my particular excel instance e.g. after app crash. I can eventually kill all hidden excels with this snippet.
List<Process> procs = new List<Process>();
procs.AddRange(Process.GetProcessesByName("excel"));
foreach (Process p in procs)
if ((int)p.MainWindowHandle == 0)
{ //Kill excel
I have observed only one problem: when user tries to open excel file from explorer using file association, it somehow finds and shows my hidden instance and the required file does not appear in Excel. When excel is opened just running excel.exe e.g from desktop shortcut then a new instance is opened and it is ok.