C# Excel to Gridview 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);


        GridView1.DataSource = ds;

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?


\ 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""");

Need Your Help

Phone Numbers: String or Int?

java string integer software-engineering vcard

I am creating a phonebook program. It can read VCards. The problem is with phone numbers. You know normally, a phone number will be like this.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.