【问题标题】:how to read an excel file which has no path如何读取没有路径的excel文件
【发布时间】:2017-03-22 07:11:22
【问题描述】:

我一直在使用此代码读取一个 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);
      }
    }
}

打开一个每秒更新数据的 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 文件?

提前致谢。

【问题讨论】:

  • 你有没有想过更新excel文件的应用程序也会锁定它?
  • 它没有被锁定。它每秒更新一次

标签: c# process


【解决方案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;

【讨论】:

  • 我猜你没有得到我的问题。该过程没有可供阅读的路径。读取路径中没有文件。它只是一个使用ms excel打开的进程,没有任何源路径。
  • 除非 MS Excel 在更新文件时移动文件,否则它应该就在那里 :) 文件在 Windows 资源管理器中吗?
  • yes C:\Program Files (x86)\Microsoft Office\Office12\Excel.exe 是显示的路径。但是当我尝试打开该文件时,正在打开一个新的 Excel 表。因此它得出的结论是文件正在打开而没有路径.. :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-21
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
相关资源
最近更新 更多