简体   繁体   中英

Importing data from Excel to database in Entity Framework

I am new to model view controller and Entity Framework and I am designing a web application and I need to import data from Excel into a database.

I am having problem importing the data fields like date and I want that it take some values from my controller and some values from Excel.

For example if I have 3 fields (Name, product and date), then I want to import from Excel (Name and product) and it will take date by default in every row.

http://mvc4beginner.com/Sample-Code/ImportExportExcelData/MVC4-Import-ExcelData-to-Database.html

This is helping to import data from Excel but I am not able to take values of date and not able to give values by default.


public ActionResult Importexcel()
    {


        if (Request.Files[" fileupload1"].ContentLength > 0 && !string.IsNullOrEmpty(Request.Files["fileupload1"].FileName))
        {
            string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);
            string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["FileUpload1"].FileName);
            if (System.IO.File.Exists(path1))
                System.IO.File.Delete(path1);

            Request.Files["FileUpload1"].SaveAs(path1);
            string sqlConnectionString = @"Data Source=(LocalDb)\ProjectsV12;AttachDbFilename=|DataDirectory|\BlueWhaleDB.mdf;Initial Catalog=BlueWhaleDB;Integrated Security=True";


            //Create connection string to Excel work book
            string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False";
            //Create Connection to Excel work book
            OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
            //Create OleDbCommand to fetch data from Excel
            OleDbCommand cmd = new OleDbCommand("Select [Id],[ClientId],[InstituteId],[AdmissionId],[PreviousAdmissionId],[DateOfAdmission],[ClassId],[Class],[SectionId],[Section],[RollNumber],[FirstName],[MiddleName],[LastName],[GenderId],[DateOfBirth],[CategoryId],[StudentTypeId],[Session],[IsDeactivated],[DeactivatedDate],[ModifiedBy],[ModifiedDate] from [Student$]", excelConnection);

            excelConnection.Open();

            //OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);
            //DataTable dReader = new DataTable();
            //DataSet objDataset1 = new DataSet();

            OleDbDataReader dReader;

            //for (int i = 0; i < dReader.Rows.Count; i++)
            //{
            //    new StudentViewModel
            //    {
            //        Id = dReader.Rows[i][1];

            //};



            //if (dReader.Rows[0][6].ToString() == DateTime.MinValue)
            //{
            //    dReader.Rows[i][6] = DateTime.Now;
            //}

            //else if (dReader.Rows[0][22].ToString() == "")
            //{
            //    dReader.Rows[i][22] = DateTime.Now;
            //}

            //else if (dReader.Rows[0][21].ToString() == "")
            //{
            //    dReader.Rows[i][21] = "System";
            //}

            //else if (dReader.Rows[0][19].ToString() != "")
            //{
            //    dReader.Rows[i][19] = false;
            //}
            dReader = cmd.ExecuteReader();

            SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlConnectionString);
            //Give your Destination table name
            sqlBulk.DestinationTableName = "Student";
            sqlBulk.WriteToServer(dReader);
            excelConnection.Close();

            // SQL Server Connection String


        }

        return RedirectToAction("Student");
    }

This is the code i am using please suggest me according to this code

With the help of OleDbDataAdapter.

Below is the sample code.

Query = "Select [id],[Name],[Marks],[Grade] from [Sheet1$]";
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand(Query, excelCon);
//System.Data.OleDb.OleDbDataReader dReader;              
DataSet ds = new DataSet();
OleDbDataAdapter oda = new OleDbDataAdapter(Query, excelCon);
excelCon.Close();
oda.Fill(ds);
DataTable Exceldt = ds.Tables[0];

foreach (DataRow dr in Exceldt.Rows)
{
   ExampleModel NewModel= new ExampleModel ();
   //Pass values to model whatever your model is.
   //Add to your dbContext
   dbContext.tableName.Add(NewModel);
   dbContext.SaveChanges();
}
return RedirectToAction("Import");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM