table

The above is sample excel sheet for demo.

I have named it as StudentDetails.

Here is steps to read all the records to datatable

Step 1: Create a oledb connection,command and adapter fields.

Step 2: Create method like to initialize oledb connection string.

  1. void InitializeOledbConnection(string filename, string extrn)
  2. {
  3. string connString = "";
  4. if (extrn == ".xls")
  5. //Connectionstring for excel v8.0
  6. connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + your excel file path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
  7. else
  8. //Connectionstring fo excel v12.0
  9. connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + your excel file path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";
  10. OledbConn = new OleDbConnection(connString);
  11. }
Step 3: Create a method like below to read records from excel file I name it as ReadFile().
  1. private DataTable ReadFile()
  2. {
  3. try
  4. {
  5. DataTable schemaTable = new DataTable();
  6. OledbCmd = new OleDbCommand();
  7. OledbCmd.Connection = OledbConn;
  8. OledbConn.Open();
  9. OledbCmd.CommandText = "Select * from [StudentDetails$]";
  10. OleDbDataReader dr = OledbCmd.ExecuteReader();
  11. DataTable ContentTable = null;
  12. if (dr.HasRows)
  13. {
  14. ContentTable = new DataTable();
  15. ContentTable.Columns.Add("Name", typeof(string));
  16. ContentTable.Columns.Add("RollNo", typeof(string));
  17. ContentTable.Columns.Add("Dept", typeof(string));
  18. while (dr.Read())
  19. {
  20. if (dr[0].ToString().Trim() != string.Empty && dr[1].ToString().Trim() != string.Empty && dr[2].ToString().Trim() != string.Empty && dr[0].ToString().Trim() != " " && dr[1].ToString().Trim() != " " && dr[2].ToString().Trim() != " ")
  21. ContentTable.Rows.Add(dr[0].ToString().Trim(), dr[1].ToString().Trim(), dr[2].ToString().Trim());
  22. }
  23. }
  24. dr.Close();
  25. OledbConn.Close();
  26. return ContentTable;
  27. }
  28. catch (Exception ex)
  29. {
  30. throw ex;
  31. }
  32. }
Step 4: Now we reached the file step to invoke all the methods we created.

I just call the above methods in btn click event.
  1. protected btnimport_click(object sender, eventargs e)
  2. {
  3. InitializeOledbConnection(“C:\Sample.xls”,”.xls” );
  4. DataTable tempTable= ReadFile();
  5. }
That is it :)