Search code examples
c#asp.net-mvcmodel-view-controllerimport-from-excel

Import excel to database add date now


I have a working code of importing excel to database in mvc. In these i have a date column which leaves blank after the import. What i want is to insert the date now upon import.

This is my code as of now:

[HttpPost]
public ActionResult UploadCsv(HttpPostedFileBase attachmentcsv, Device device)
{
    CsvFileDescription csvFileDescription = new CsvFileDescription
    {
        SeparatorChar = ',',
        FirstLineHasColumnNames = true
    };
    CsvContext csvContext = new CsvContext();
    StreamReader streamReader = new StreamReader(attachmentcsv.InputStream);
    IEnumerable<Device> list = csvContext.Read<Device>(streamReader, csvFileDescription);
    db.Devices.AddRange(list);
    // code for insert Date now on my date column because it leaves blank
    db.SaveChanges();
    return RedirectToAction("Index","Devices");
}

Solution

  • I assume your database property name is UploadDateTime in device class.

    List<Device> list = csvContext.Read<Device>(streamReader, csvFileDescription).ToList();
    
    //Use below line of code to assign datetime to all object in list then add and save.
    list.ForEach(x=> x.UploadDateTime = DateTime.Now);
    
    db.Devices.AddRange(list);
    // code for insert Date now on my date column because it leaves blank
    db.SaveChanges();
    

    EDIT

    if list.ForEach doesn't work then you can use like this

    //or u can use foreach like below 
    foreach ( var item in list)
    {
        item.UploadDateTime = DateTime.Now;
    }