public void LoadData(string strFile)
{
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=" + strFile + ";Extended Properties='Excel 12.0;HDR=YES;'";
// If you don't want to show the header row (first row) use 'HDR=NO' in the string
string strSQL = "SELECT * FROM [Sheet1$]";
OleDbConnection oleConnection = new OleDbConnection(connectionString);
oleConnection.Open(); // This code will open excel file.
using (OleDbCommand dbCommand = new OleDbCommand(strSQL, oleConnection))
{
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(dbCommand))
{
// create data table
using (DataTable dTable = new DataTable())
{
dataAdapter.Fill(dTable);
foreach (DataRow item in dTable.Rows)
{
// Do something
}
}
}
}
oleConnection.Close();
oleConnection.Dispose();
}
Happy Coding :)
Read Data or Spreadsheet From Microsoft Excel 2007 using Csharp (Snippet)
If you want to read data from MS Excel 2007. See the below snippet.