string connectionString = "";
if (FileUpload.HasFile)
{
string fileName = Path.GetFileName(FileUpload.PostedFile.FileName);
string fileExtension = Path.GetExtension(FileUpload.PostedFile.FileName);
string fileLocation = Server.MapPath("~/upload/" + fileName);
FileUpload3.SaveAs(fileLocation);
//Check whether file extension is xls or xslx
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
//Create OleDB Connection and OleDb Command
try
{
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
OleDbDataReader odr = cmd.ExecuteReader();
string usr = "";
string name = "";
string surname = "";
while (odr.Read())
{
usr = valid(odr, 1); // in the column 1 we find the user
string name = valid(odr, 2); // in the column 2 we find the name of the user
string surname = valid(odr, 3); // in the column 3 we find the surname of the user
Insert(usr, name, surname); // put the data in the database with your custom function Insert
}
con.Close();
}
catch (DataException ex)
{
lblResponse.Text = ex.Message;
}
}
Reference :-
Read Excel File into DataSet in ASP.NET Using C#[
^]