Ivan
Ivan

Reputation: 1

Syntax error when opening an Excel workbook using C#

When I try to open an Excel workbook I get a syntax error. Here is the code I'm using:

string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" 
                          + "Data Source=" + fileName + ";"
                          +"Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";";
OleDbConnection objConn = new OleDbConnection(connectionString);
OleDbCommand objCommand = new OleDbCommand(@"SELECT * FROM Sheet1$", objConn);
OleDbDataAdapter odjAdp = new OleDbDataAdapter();
odjAdp.SelectCommand = objCommand;
DataTable dt1 = new DataTable();
odjAdp.Fill(dt1);
GridView2.DataSource = dt1;
GridView2.DataBind();

Why is this happening?

Upvotes: 0

Views: 255

Answers (1)

Alex K.
Alex K.

Reputation: 175936

Because of the dollar symbol that sheet name needs to be escaped, enclose it in square brackets;

@"SELECT * FROM [Sheet1$]"

Upvotes: 1

Related Questions