如何读取没有路径的excel文件

时间:2017-03-22 07:11:23

标签: c# process

我一直在使用此代码来读取excel文件,当我尝试读取已保存的Excel文件时,它工作正常

string con = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;" +   @"Extended Properties='Excel 8.0;HDR=Yes;'";    

using(OleDbConnection connection = new OleDbConnection(con))
{
   connection.Open();
   OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", 
   connection); 
   using(OleDbDataReader dr = command.ExecuteReader())
    {
      while(dr.Read())
      {
         var row1Col0 = dr[0];
         Console.WriteLine(row1Col0);
      }
    }
}

theres和应用程序打开一个excel文件,每秒更新数据,这里是应用程序的图片

在这里你可以看到在任务栏中打开的excel文件。当我使用进程代码使用这段代码读取excel文件的路径时我没有数据,因为该路径中的文件是空的

Process [] processlist = Process.GetProcesses();

        foreach (Process theprocess in processlist)
        {
            if (theprocess.ProcessName == "EXCEL")
            {
                Console.WriteLine(theprocess.ProcessName, theprocess.Id);
                string fullPath = theprocess.MainModule.FileName;
                //fullpath = C:\\Program Files (x86)\\Microsoft Office\\Office12\\EXCEL.EXE

            }
        }

应用程序可能正在直接使用ms excel的实例。是否有任何替代步骤直接通过进程ID而不是路径来读取此excel文件?

提前致谢。

1 个答案:

答案 0 :(得分:1)

Processes不应该以这种方式使用。您可以启动,停止和终止Process,但无法访问它的内存并使用它读取文件(实际上是任何数据流)。我也认为没有办法通过Process类访问打开文件的路径。

但是,使用Office Interop COM API,您可以获取当前文件,包括Application.ActiveWorkbook.FullName的路径。

请注意,只有打开一个Excel实例时,此解决方案才有效。

Microsoft.Office.Interop.Excel.Application MyExcelApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
string FullPath = MyExceAppl.ActiveWorkbook.FullName;