我正在尝试构建一个允许用户选择以前打开的Excel实例的表单。
从那里,我想提取与该打开的实例关联的.xlsx
文件的名称。
我怀疑我必须使用COM才能将它从那里拿出来,但我还没有找到办法。
我想的代码如下:
Process[] openApplications = Process.GetProcessesByName("excel");
foreach(Process p in openApplications)
{
///Find the associated .xlsx path and file
///...Maybe from the handle id?
}
非常感谢任何帮助
答案 0 :(得分:1)
您必须使用ActiveWorkbook
属性。
请参阅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)
{
}
答案 1 :(得分:0)
首先,您必须添加对Microsoft Excel Object Library的引用以获取正在运行的MS Excel应用程序的实例:
var application = (Application)Marshal.GetActiveObject("Excel.Application");
然后,您可以通过ActiveWorkbook和FullName属性获取文件的完整路径。
Console.WriteLine(application.ActiveWorkbook.FullName);
如果您打开了多个MS Excel实例,则可以通过Workbooks属性迭代它们:
foreach (Workbook workbook in application.Workbooks)
{
// do something with workbook.FullName
}