Search code examples
c#asp.netexcelgridviewoledb

C# Excel file import to GridView causes OleDB Error


I got an error about OleDB. I just want my excel file import to GridView.

Here is my code.

string connstr = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=C:\a.xls;Extended Properties=Excel 8.0;HDR=YES;IMEX=1";

OleDbConnection conn = new OleDbConnection(connstr);

string strSQL = "Select * from [Sheet1$]";

OleDbCommand cmd = new OleDbCommand(strSQL, conn);

DataSet ds = new DataSet();

OleDbDataAdapter da = new OleDbDataAdapter(cmd);

da.Fill(ds);

GridView1.DataSource = ds;
GridView1.DataBind();

When I build project there is no error, but when I run this project, I got an error like this:

System.ArgumentException:Format of the initialization string does not conform to specification starting at index 47.

Line 21: string connstr = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=C:\a.xls;Extended Properties=Excel 8.0;HDR=YES;IMEX=1"; Line 22: Line 23:
OleDbConnection conn = new OleDbConnection(connstr);

How can I fix this?


Solution

  • \ is a special char in c# string literals. To specify paths in a string in c# either use escaping:

    string path = "C:\\myFolder\\myfile.xls";
    

    or use verbatim strings:

    string path =@"C:\myfolder\myfile.xls";