如何获得确切数量的工作簿(excel文件)

时间:2016-02-09 11:21:18

标签: c# ms-office

如何获取excel文件的总数。我正在使用以下代码打开我的文件

try
   {
      var excelApp = new Excel.Application();
      excelApp.Visible = true;
      Excel.Workbooks book = excelApp.Workbooks;
      Excel.Workbook sheets = book.Open(schemes.ProcessExefilePath);
    }
 catch (Exception ex)
        {
        }

然后当我获得文件总数时。它总是给我零计数

  Microsoft.Office.Interop.Excel.Application excelApp = null;

    try
     {
        excelApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
      }
    catch
        {

         }
    if (excelApp == null)
       {
        excelApp = new Microsoft.Office.Interop.Excel.Application();
        }

         for (int i = 0; i < excelApp.Windows.Count; i++)
          {
                       //my work....... 
           }

这段代码有什么问题..还是我还有其他事情要做..

enter image description here

1 个答案:

答案 0 :(得分:2)

在您的代码中,您不会在声明的excelApp中打开任何文件,因此Windows.count会为您提供值0

尝试:

Microsoft.Office.Interop.Excel.Application excelApp = null;

try
 {
    excelApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
  }
catch
    {

     }
if (excelApp == null)
   {
    excelApp = new Microsoft.Office.Interop.Excel.Application();
    }
    ' **HERE** - Open workbooks with excelApp.Workbooks.Open(...)
     for (int i = 0; i < excelApp.Windows.Count; i++)
      {
                   //my work....... 
       }