2

I'm trying to write a class that will read information from an excel file, but for some reason, it will only run exception-free if the file in question is open in excel. Otherwise, the class throws an OleDbException. The code is as follows:

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

The error is thrown on conn.Open(), and only occurs when I don't have File.xls open in excel at the same time. Can someone help me fix this? I am not well versed enough with OLEDB to figure out why this is happening. Thanks!

  • Side note: you dont need the `@` with `connString` :) –  Jul 07 '14 at 14:32
  • 3
    Care to share the exact error message? Might be helpful here :) – hschne Jul 07 '14 at 14:36
  • I neglected to mention that the file in question was originally a .txt forced into an xls format. I went back and actually copied the data over to a new excel file, and that fixed the issue. I guess the conflicting file formats were confusing the connection. – Deepmeister Jul 07 '14 at 17:07

0 Answers0