c# - OLEDB读取Excel的性能

标签 c# performance excel oledb

以下代码在 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);

最佳答案

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

我已经复制了你的代码并放入了一个按钮点击事件,只是做了一点改动以确保为每次测试处理适配器和连接。

// 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);
        }
    }

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

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

    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);
            }
        }
    }

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

关于c# - OLEDB读取Excel的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11312661/

相关文章:

c# - 如何确定剪贴板内容的编码

c# - 循环 - 计算出的最后一个元素不同

Java:在列表上调用clear()会立即释放内存吗?

excel - 在路径中间找到一个字符串

java - 每次读取一行/仅读取特定列并创建对象

c# - 质数公式

c# - WPF:使窗口不可调整大小,但保留框架?

xml - 下载和解析 XML 的最有效方式

c - c - 如何在c中比fprintf更快地写入文本文件?

excel - 通过 Workbook_SheetFollowHyperlink() VBA 调用函数会导致过程声明错误