How To Upload And Read CSV File In ASP.Net MVC

In this tutorial i am going to explain about How To Upload And Read CSV File In C#ASP.Net MVC. In my previous tutorial i have explained about

Implementation :

Now we will see the implementation of How To Upload And Read CSV File In C#ASP.Net MVC

For explaining purpose i have created a new asp.net mvc project. After that right click on project and select Manage Nuget Packages and search for Entity Framework

How To Upload And Read CSV File In C#, ASP.Net MVC

Select Entity Framework latest version and click install.

Step 2 of How To Upload And Read CSV File In C#, ASP.Net MVC

Once entity framework is installed, click on models folder and add a class called Employee.cs

Step 3 of How To Upload And Read CSV File In C#, ASP.Net MVC

Employee.cs will contain below propertis.

And now again right click on models folder and add a new class called DemoContext.cs. This will inherit from DBContext class. Below is my DemoContext.cs code

I have added the connection string in web.config file.

Add Controller:

Once context class is created it is time to add controller. Now right click on the controllers folder and choose Add=> Controller option. Name the controller as ImportController.cs

Step 5 of How To Upload And Read CSV File In C#, ASP.Net MVC

Add View:

The controller has a get method with action named Index and post method with action named as Index. Now right click on the action name and add view.

Step 6 of How to read data from excel sheet and insert into database table using C#, ASP.Net MVC

The view contains below information

  1. File Upload control to choose and upload files
  2. Submit button to post the selected file for processing
  3. Viewbag.Message to show any success,error or warning messages

Below is the complete view code.

Import Controller Code:

Below is my complete controller code.

Add New View:

Lets add a view now  to display imported records. Right click on Views=> Import folder and choose Add=>View option. Refer the below screenshot.

Step 7 of How To Upload And Read CSV File In C#, ASP.Net MVC

Add the below code in the View.cshtml file.

Output:

Now if you run the program you can see the output of How To Upload And Read CSV File In C#ASP.Net MVC.

How To Upload And Read CSV File In C#, ASP.Net MVC

Source Code:

Source code of How To Upload And Read CSV File In C#, ASP.Net MVC

Conclusion:

Hope you learned How To Upload And Read CSV File In C#ASP.Net MVC. Do you like this tutorial? Help us to improve. Please post your comments and feedback below.

Leave a Reply

Your email address will not be published. Required fields are marked *