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(con开发者_开发技巧nstr);
How can I fix this?
\ 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";
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""");
精彩评论