我希望将我的发现作为答案呈现,因为这种行为始终如一。
我复制了您的代码并放在一个按钮点击事件中,只是稍微更改了一下,以确保在进行每个测试时处理适配器和连接。
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);
}
}
所以,这基本上是你的代码。这段代码在500ms内执行。但是...
如果我在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);
}
}
}
而且,不,它并不是OleDbConnection的Open()方法,而始终是adapter.Fill()方法。