0
votes

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?

2

2 Answers

1
votes

\ 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";
1
votes

Your string connstr needs double quotes for the Extended Properties values. e.g.:

OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + PrmPathExcelFile + @";Extended Properties=""Excel 8.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text""");