Export Data to Excel with ASP.NET MVC

In creating a system there are times that we need to export data to excel, it could either be for reports or for data examination. This is what this article is all about.

Below are one of those method. To start, we need to create a fresh project of ASP.NET MVC. If this is your first time in creating ASP.NET MVC, you may refer to this article “How to start with ASP.NET MVC“.

Output Preview:

Export data to excel

Final Output

Let’s start:

I assume you have already created a new project with default MVC template.

First, open HomeController. Located inside Controller folder, remove all action result except for index().

It should look like this:

Export data to excel

Home Controller

Second, let’s create a view where we can display sample data into a table.To open your view navigate to Views->Home->index.cshtml or simply right click inside index action result and select Go to View.

Export data to excel

Navigate to View

Replace all code from your index.cshtml with the code below.

Export to excel

Employee Age Address BirthDate BirthPlace

 

 

Third, create a model class inside Models folder. This will be used in creating our sample data and declare all properties shown below.

Code:

Image preview:

Export data to excel

TableModel

Fourth, Create a sample data. Navigate back to your HomeController and create method sample_data. 

Code:

Fifth, fill html table that we created a while ago using Jquery. Navigate back to your controller view.Add the code below.

Code:

Lastly, create exportToExcel method inside your HomeController.

Code:

And we’re done… To run project simply press F5 key from your keyboard. Thank you for reading.. Happy coding!!

To review your work please refer from the full code below… 🙂

Full Code:

TableModel.cs

HomeController.cs

Index.cshtml

Final output:

Export data to excel

Final Output


Post you may like:

[pt_view id=”2384ae03it”]

Leave a Reply

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