2

I'm trying to build a form that allows a user to select a previously opened Excel instance.

From there, I want to extract out the name of the .xlsx file associated with that opened instance.

I suspect I'll have to use COM to get it out of there, but I haven't found a way to do it.

The code I'm thinking is as follows:

Process[] openApplications = Process.GetProcessesByName("excel");

foreach(Process p in openApplications)
{
    ///Find the associated .xlsx path and file
    ///...Maybe from the handle id?
}

Any help would be much appreciated

Sid M
  • 4,354
  • 4
  • 30
  • 50
Tim C
  • 47
  • 1
  • 7

2 Answers2

1

You have to use the ActiveWorkbook property. Please refer this.

        try
        {
            Process[] openApplications = Process.GetProcessesByName("excel");
            int proLen = openApplications.Length;
            if (proLen == 0)
            {
                Console.WriteLine("The process does NOT exist or has exited...");
                return 0;
            }

            foreach(Process p in openApplications)
             {
             //validate p for null/nothing
             //get the name of the workbook using
             //Use p.ActiveWorkbook.Name to get the file name.
             }        
            return 1;
        }
        catch (Exception ex)
        {

        }
Sid M
  • 4,354
  • 4
  • 30
  • 50
Rahul Vishwakarma
  • 996
  • 5
  • 17
  • 35
0

First, you'll have to add a reference to the Microsoft Excel Object Library to get an instance of the running MS Excel application:

var application = (Application)Marshal.GetActiveObject("Excel.Application");

Then you can get the full path of the file via ActiveWorkbook and FullName properties.

Console.WriteLine(application.ActiveWorkbook.FullName);

And if you have more than one instance of MS Excel opened, you can iterate over them via Workbooks property:

foreach (Workbook workbook in application.Workbooks)
{
    // do something with workbook.FullName
}
Yurii
  • 4,811
  • 7
  • 32
  • 41
  • I get an exception when I do the var application = ... Also, what do I do if there are multiple open workbooks? I'm trying to allow the user to select the active one... – Tim C Jul 17 '14 at 11:08
  • @TimC, that's not a very informative description of what's happening. Make sure you use object library of the version that corresponds to the target version of MS Excel; try searching the net for the problem described in the exception message; if it doesn't help, you can ask a new question, but please do include all the relevant information, [some tips](http://stackoverflow.com/help/mcve). – Yurii Jul 17 '14 at 11:20