Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an open Excel Workbook in C#

I need to access an excel file that is already open. I thought just inspecting the .Workbooks property that it would be there but it isn't. What is the right way to get a reference to the open workbook?

var app = new Microsoft.Office.Interop.Excel.Application();

// the count is 0 =(
app.Workbooks.Count == 0;

EDIT

I can get a reference to the Excel Application via...

app = (Excel.Application)Marshal.GetActiveObject("Excel.Application");

but app.Workbooks.Count is still 0 why isn't it able to get a reference to the opened workbook?

like image 237
Jon Erickson Avatar asked Jul 13 '11 16:07

Jon Erickson


1 Answers

Instead of instantiating a new instance, check for an existing one:

try
{
  Microsoft.Office.Interop.Excel.Application app = 
      System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
}
catch
{
  // Excel is not running.
}
like image 107
Armbrat Avatar answered Sep 28 '22 14:09

Armbrat