我正在编写一个应用程序来打开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秒才能完成,这与interop 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);发布于 2014-04-22 06:40:33
这个答案只是关于你问题的第二部分。您正在使用的范围很多,这不是预期的,而且确实非常缓慢。
首先读取整个范围,然后按如下方式迭代结果:
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());
}
}这样会快得多!
发布于 2014-04-22 16:23:56
在@RvdK的回答后,互操作是缓慢的。
为什么这么慢?
这是因为它是如何工作的。从.NET发出的每个调用都必须封送到本地COM代理--必须从一个进程(应用程序)封送到COM服务器(Excel) (通过Windows内核内部的IPC ),然后将其从服务器的本地代理转换(分派)为本机代码,其中从OLE自动化兼容类型封送参数到本机类型,检查它们的有效性并执行函数。结果表明,该函数通过两个不同的过程之间的几个层,返回的方式大致相同。
因此,每个命令的执行成本都很高,执行得越多,整个过程就越慢。您可以在web上找到大量的文档,因为COM是一个古老且工作良好的标准(在某种程度上使用Visual 6)。
这篇文章的一个例子是:http://www.codeproject.com/Articles/990/Understanding-Classic-COM-Interoperability-With-NE
有更快的阅读方式吗?
发布于 2014-04-22 06:32:40
简短的回答:正确,互操作很慢。(同样的问题,花了几秒钟读了300行.
为此使用一个库:
https://stackoverflow.com/questions/23212027
复制相似问题