tags:

views:

719

answers:

2

I need to finish an application in C#. Now I want to get a function that control a Excel file to get data. I used getActiveObject("Excel.Application"), but this returns nothing. And more, I can't use Excel.Application in VS2008 , and Microsoft.Office.Interop.Excel.Application is instead of it. So is there another way to get what I want?

Microsoft.Office.Interop.Excel.Application e = (Microsoft.Office.Interop.Excel.Application)Marshal.GetActiveObject("Excel.Application");

A: 

In order to be able to refer to the Excel object model as "Excel", then you can create an alias via a using statement at the top of your namespace (or document) as follows:

using Excel = Microsoft.Office.Interop.Excel;

Thereafter, you can refer to Excel.Application instead of the long-winded Microsoft.Office.Interop.Excel.Application.

As for why your call to Marshal.GetActiveObject is failing, I can't say for sure. A couple of thoughts:

(1) Are you certain that there is a running instance of Excel already present? If not, then create a new Excel application:

Excel.Application xlApp = new Excel.Application();

(2) If there definitely is an Excel application already running, then it is possible that the Excel instance has not yet been added to the Running Objects Table (ROT) if the Excel Application has never lost focus. See: Visual C# .NET Error Attaching to Running Instance of Office Application for more on this. I believe that the Marshal.GetActiveObject method should throw an exception in this case -- not quietly return null -- but this still seems potentially relevant.

I hope this helps...

Mike

Mike Rosenblum
A: 

After about a half a day of playing around I finally figured out how to make this work so you can latch onto an open copy of excel. My users have been complaining mightily about having too many instances of Excel open.

Here is a snippet of what I did to get it working:

_Application excelApp;

try
{
  excelApp = (_Application)Marshal.GetActiveObject("Excel.Application");
}
catch(Exception)
{
  // this is important. If Excel is not running, GetActiveObject will throw
  // an exception
  excelApp = null;
}

if( excelApp == null )
{
  excelApp = new ApplicationClass();
}

I have been chasing this for a while and finally had some time to hunker down and figure it out.

Jager