林克到Excel的速度非常慢

本文关键字:非常 速度 Excel 林克 | 更新日期: 2023-09-27 18:30:13

我正在尝试创建一个应用程序,该应用程序将从自动生成的excel文件中提取一些数据。使用Access可以很容易地做到这一点,但文件在Excel中,解决方案必须是一键式的。

出于某种原因,简单地在数据中循环而不执行任何操作是很慢的。下面的代码是我尝试从速度慢得多的地方对其进行优化。在直接使用Interop类并通过不同的包装器进行了几次尝试之后,我已经开始使用Linq-to-SQL了。

我也在这里和谷歌上阅读了一些问题的答案。为了弄清楚是什么导致了速度慢,我删除了所有指令,但在相关部分保留了"I++"。它仍然很慢。我还试图通过限制第三行where子句中检索到的记录数量来优化它,但这没有奏效。非常感谢您的帮助。

谢谢。

        Dictionary<string,double> instructors = new Dictionary<string,double>();
        var t = from c in excel.Worksheet("Course_201410_M1")
               // where c["COURSE CODE"].ToString().Substring(0,4) == "COSC" || c["COURSE CODE"].ToString().Substring(0,3) == "COEN" || c["COURSE CODE"].ToString().Substring(0,3) == "GEIT" || c["COURSE CODE"].ToString().Substring(0,3) == "ITAP" || c["COURSE CODE"] == "PRPL 0012" || c["COURSE CODE"] == "ASSE 4311" || c["COURSE CODE"] == "GEEN 2312" || c["COURSE CODE"] == "ITLB 1311"
                select c;
        HashSet<string> uniqueForce = new HashSet<string>();
        foreach (var c in t)
        {
            if(uniqueForce.Add(c["Instructor"]))
                instructors.Add(c["Instructor"],0.0);
        }
        foreach (string name in instructors.Keys)
        {
            var y = from d in t
                    where d["Instructor"] == name
                    select d;
            int i = 1;
            foreach(var z in y)
            {
                //this is the really slow. It takes a couple of minutes to finish. The 
                // file has less than a 1000 records.
                i++;
            }

        }

林克到Excel的速度非常慢

将形成var t的查询放入括号中,然后对其调用ToList()。

     var t = (from c in excel.Worksheet("Course_201410_M1")
     select c).ToList();

由于linq的延迟/延迟执行模型,每当您迭代集合时,它都会重新查询数据源,除非您给它一个List。