编程语言
首页 > 编程语言> > c# – Interop Excel很慢

c# – Interop Excel很慢

作者:互联网

我正在编写一个应用程序来打开Excel工作表并阅读它

MyApp = new Excel.Application();
MyBook = MyApp.Workbooks.Open(filename);
MySheet = (Excel.Worksheet)MyBook.Sheets[1]; // Explict cast is not required here
lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
MyApp.Visible = false;

这需要大约6-7秒才能完成,这是正常的互操作Excel吗?

还有一种比这更快的阅读Excel的方法吗?

string[] xx = new string[lastRow];
for (int index = 1; index <= lastRow; index++)
{
   int maxCol = endCol - startCol;
   for (int j = 1; j <= maxCol; j++)
   {
      try
      {
         xx[index - 1] += (MySheet.Cells[index, j] as Excel.Range).Value2.ToString();
      }
      catch
      {    
      }

      if (j != maxCol) xx[index - 1] += "|";
   }
}
MyApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(MySheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(MyBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(MyApp);

解决方法:

这个答案只是关于你问题的第二部分.
你在那里使用很多范围,这些范围不是预期的,实际上非常慢.

首先阅读完整范围,然后迭代结果,如下所示:

var xx[,] = (MySheet.Cells["A1", "XX100"] as Excel.Range).Value2;
for (int i=0;i<xx.getLength(0);i++)
{
    for (int j=0;j<xx.getLength(1);j++)
    {
         Console.WriteLine(xx[i,j].toString());
    }
}

这会快得多!

标签:c,excel,excel-interop
来源: https://codeday.me/bug/20190517/1119927.html