OLEDB读取Excel的性能

hrz*_*fer 5 c# oledb excel performance

以下代码在i7-*3.4 GHz windows-7 64位计算机上花费大约2500毫秒来读取具有25000行和5列的excel表.每个单元格大约包含一个10个字符的字符串.这是正常的吗?我怎样才能更快地阅读它?

 Stopwatch sw1 = Stopwatch.StartNew();
 var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; " +
                                             "Extended Properties=Excel 12.0;", filename);

 var adapter = new OleDbDataAdapter("SELECT * FROM [roots$]", connectionString);
 var ds = new DataSet();
 adapter.Fill(ds, "roots");
 sw1.Stop(); Console.WriteLine("Time taken for excel roots: {0} ms", sw1.Elapsed.TotalMilliseconds);
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 6

我希望将我的发现作为答案,因为行为总是一致的.

我已经复制了你的代码并放入了一个按钮点击事件,只是稍微改了一下,确保为每次测试都配置了适配器和连接.

// test.xls contains 26664 rows by 5 columns. Average 10 char for column, file size is 2448kb
// OS Windows 7 Ultimate 64 bit. CPU Intel Core2 Quad Q9550 2.83ghz 
// 8gb ram and disk C is an 256gb SSD cruzer

    private void button1_Click(object sender, EventArgs e)
    {

        string filename = "c:\\tmp\\test.xls";
        Stopwatch sw1 = Stopwatch.StartNew(); 
        var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; " + 
                                              "Extended Properties=Excel 12.0", filename);

        using(var adapter = new OleDbDataAdapter("SELECT * FROM [roots$]", connectionString))
        {
            var ds = new DataSet();
            adapter.Fill(ds, "roots");
            sw1.Stop();
            Console.WriteLine("Time taken for excel roots: {0} ms", sw1.Elapsed.TotalMilliseconds);
        }
    }
Run Code Online (Sandbox Code Playgroud)

所以,这基本上就是你的代码.此代码在500毫秒内执行.但是.... 如果我在Excel 2010中保持文件test.xls打开,执行时间会跳到8000ms.

我也试过这个代码变体,但最终结果是一样的

    private void button1_Click(object sender, EventArgs e)
    {
        string filename = "c:\\tmp\\test.xls";
        Stopwatch sw1 = Stopwatch.StartNew(); 
        var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; " + 
                                              "Extended Properties=Excel 12.0", filename);
        using(OleDbConnection cn = new OleDbConnection(connectionString))
        {
            cn.Open();
            using(var adapter = new OleDbDataAdapter("SELECT * FROM [roots$]", cn))
            {
                var ds = new DataSet();
                adapter.Fill(ds, "roots");
                sw1.Stop();
                Console.WriteLine("Time taken for excel roots: {0} ms", sw1.Elapsed.TotalMilliseconds);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

并且,不,它不是OleDbConnection的Open(),始终是adapter.Fill()