我希望将我的发现作为答案提出,因为行为始终是一致的。
我已经复制了您的代码并将其放入按钮单击事件中,只是进行了一些更改以确保为进行的每个测试处理适配器和连接。
// 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()