除非文件已经打开,否则无法连接到Excel文件

时间:2014-07-07 14:27:28

标签: c# excel

我正在尝试编写一个将从excel文件中读取信息的类,但出于某种原因,如果有问题的文件在excel中打开,它将只运行无异常。否则,该类抛出OleDbException。代码如下:

String filename = @"C:\Users\me\Documents\File.xls";
string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;HDR=YES'";
using (OleDbConnection conn = new OleDbConnection(connString))
{
conn.Open();
OleDbCommand selectCommand = new OleDbCommand("select * from [Sheet1$]", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(selectCommand);
DataTable dt = new DataTable();
adapter.Fill(dt);
int counter = 0;
foreach (DataRow row in dt.Rows)
{
    String dataA= row["DataA"].ToString();
    String dataB= row["DataB"].ToString();
    Console.WriteLine(DataA+ " = " + dataB);
    counter++;
    if(counter>=40)
        break;
}

conn.Open()上会抛出错误,只有在我没有同时在excel中打开File.xls时才会出现错误。有人可以帮我解决这个问题吗?我对OLEDB不够精通,无法弄清楚为什么会这样。谢谢!

0 个答案:

没有答案