How to import data from Excel file using C#

Started by admin, August 24, 2008, 06:36:17 AM

Previous topic - Next topic

admin

private void btnImportExcelToGrid_Click(object sender,
System.EventArgs e)
{
String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\\Book2.xls;" +
"Extended Properties=Excel 8.0;";

DataSet ds = new DataSet();
//You must use the $ after the object
//you reference in the spreadsheet
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Sheet1$]", strConn);

//da.TableMappings.Add("Table", "ExcelTest");

da.Fill(ds);
DataGrid2.DataSource = ds.Tables[0].DefaultView;
DataGrid2.DataBind();
}


admin

For Excel 2007 you can use the following connection string:
"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=C:\\Book2.xls;" +
"Extended Properties=Excel 12.0;"

admin


admin

Important note: if you are selecting data for a specific date you can use the following:
"SELECT * FROM [Sheet1$] where datecol=#3/15/2009#"
don't try to use the single quotes " ' ".