从进程ID获取打开的xlsx文件名

我试图build立一个表单,允许用户select一个以前打开的Excel实例。

从那里,我想提取出与打开的实例关联的.xlsx文件的名称。

我怀疑我将不得不使用COM来把它从那里,但我还没有find办法。

我在想的代码如下:

 Process[] openApplications = Process.GetProcessesByName("excel"); foreach(Process p in openApplications) { ///Find the associated .xlsx path and file ///...Maybe from the handle id? } 

任何帮助将非常感激

您必须使用ActiveWorkbook属性。 请参考这个 。

  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) { } 

首先,您必须添加对Microsoft Excel对象库的引用才能获取正在运行的MS Excel应用程序的实例:

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

然后,您可以通过ActiveWorkbook和FullName属性获取文件的完整path。

 Console.WriteLine(application.ActiveWorkbook.FullName); 

如果您打开了多个MS Excel实例,则可以通过Workbooks属性对它们进行迭代:

 foreach (Workbook workbook in application.Workbooks) { // do something with workbook.FullName }