How to Import CSV file with ASP.NET Core

In this post, we will discuss and learn how we can import CSV file in ASP.NET Core project and save the data into our database. It is very simple and easy to import CSV files in ASP.NET Core. First of all, if you have not created your project, you can create your ASP.NET Core 3-tier Application following this.

Tools:

Visual Studio Community 2019

Windows 10 OS

Let’s get started:

Before starting our procedure, we have to create a table in our database to store our data. To create a table, we are using the code-first approach.

we will create a Model/Class.

public class Student
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Class { get; set; }
    public string Roll_No { get; set; }
}

After Creating our class, we will add a reference to this class in our “ApplicationDbContext.cs” Class.

public DbSet<Student> Students { get; set; }

Now Run migration.

Add-migration

Now we will update our database.

update-database

First of All, we have to install this NuGet package into our project.

Install-Package CsvHelper -Version 27.1.1

Our CSV file looks like this, and we have encircled our header row.

import CSV file

Now we will create a class with the same properties as we have a header row in the CSV file because we have to receive data accurately from the CSV file.

public class file
{
    public string Name { get; set; }
    public string Class { get; set; }
    public string Roll_No { get; set; }
}

Here is how we will receive and store data from files in our controller or service.

public async Task<ResponseViewModel<object>> UploadData(IFormFile file)
{
  try
  {
     var fileextension = Path.GetExtension(file.FileName);
     var filename = Guid.NewGuid().ToString() + fileextension;
     var filepath = Path.Combine(Directory.GetCurrentDirectory(),   "wwwroot","files", filename);
     using (FileStream fs = System.IO.File.Create(filepath))
     {
          file.CopyTo(fs);
     }
     if(fileextension == ".csv")
     {
        using (var reader = new StreamReader(filepath))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                var records = csv.GetRecords<file>();
                foreach (var record in records)
                {

                    if (string.IsNullOrWhiteSpace(record.Name))
                    {
                        break;
                    }
                    Student student;
                    student = _context.Students.Where(s => s.Name == record.Name).FirstOrDefault();

                    if (student == null)
                    {
                        student = new Student();
                    }

                    student.Name = record.Name;
                    student.Class = record.Class;
                    student.Roll_No = record.StateWebsite;

                    if (student.Id == Guid.Empty)
                    _context.Studnets.Add(student);
                    else
                        _context.Students.Update(student);
                }
                 _context.SaveChanges();
     }
     else
     {
       return new ResponseViewModel<object>
       {
         Status = false,
         Message = "You can onlu add CSV file",
         StatusCode = System.Net.HttpStatusCode.unprocessableentiy.ToString()
       };
     }
       return new ResponseViewModel<object>
       {
          Status = true,
          Message = "Data Updated Successfully",
          StatusCode = System.Net.HttpStatusCode.OK.ToString()
       };
     }
     catch (Exception e)
     {
        await _exceptionServices.CreateLog(e, null);
        throw e;
     }
 }

Now let’s dive into our code. In the first section, we get our file and its extension, Saving its copy in our “wwwroot” folder in our application. After saving, we are checking if it’s a “CSV” file. We will check if it’s a CSV file or not, and if it is “CSV,” we will read our “CSV” file and read all the record and convert it into a “list<file>.” After that, we are applying a foreach loop on this list. In the loop, we check if there is a record that already exists in our database. If it already exists, we will update it, and if it doesn’t, we add this to our database.

Conclusion:

Try this tutorial and if you do not understand anything or face any issue while applying this method. Do not hesitate to comment below. My COde Bit team will try to respond ASAP.

See Also:

Send Emails in ASP.NET Core 5 Using Gmail API

What Is File Size Upload Limit In NFT Minting? Solution

Email Confirmation with ASP.NET Core Identity

How to Implement JWT Authentication in Asp.Net Core Web API

How to Send Emails ASP.NET Core 5 Using SMTP

Leave a Reply

Your email address will not be published.