There are many ways available to convert excel file to DataTable, I found OLEDB is best way to convert excel file to DataTable.
This is the connection String I have used:
- OleDbConnection objConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';")
This function will convert excel file to DataTable. You need to pass Excel file path and it will return DataTable.
- public static DataTable ConvertExcelToDataTable(string FileName)
- {
- DataTable dtResult = null;
- int totalSheet = 0;
- using(OleDbConnection objConn = new OleDbConnection(@
- "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';"))
- {
- objConn.Open();
- OleDbCommand cmd = new OleDbCommand();
- OleDbDataAdapter oleda = new OleDbDataAdapter();
- DataSet ds = new DataSet();
- DataTable dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
- string sheetName = string.Empty;
- if (dt != null)
- {
- var tempDataTable = (from dataRow in dt.AsEnumerable()
- where!dataRow["TABLE_NAME"].ToString().Contains("FilterDatabase")
- select dataRow).CopyToDataTable();
- dt = tempDataTable;
- totalSheet = dt.Rows.Count;
- sheetName = dt.Rows[0]["TABLE_NAME"].ToString();
- }
- cmd.Connection = objConn;
- cmd.CommandType = CommandType.Text;
- cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
- oleda = new OleDbDataAdapter(cmd);
- oleda.Fill(ds, "excelData");
- dtResult = ds.Tables["excelData"];
- objConn.Close();
- return dtResult;
- }
- }
Note
If you want to host in server, OLEDB driver need to install on server machine.