In this article we learn how to export the data into MS Excel in ASP.NET MVC without using any 3rd party libraries. If you are new to ASP.NET MVC to learn the step by step process please follow the ASP.NET MVC Series.
We take an example to print the dummy data into a ASP .NET MVC page and there we apply to export data into MS Excel.
- Create a ASP.NET MVC application using Visual Studio.
- We select as Empty project with ASP.NET MVC
- Create a Controller inside the controllers folder, let’s name as “CustomerController.cs”
- Add a customer model class in Models folder.
- In the “CustomerController” we create a dummy list that contains multiple customers. You can connect with database and fetch the real-time data.
Table of Contents
Customer Model Class
- We take a dummy data to return the customer details inside the view page.
- GetCustomer() holds the customer information.
- When Index() action method is called it collect the customer information and send to the view.
- We use the scaffolding technique to generate the list of HTML using customer model class
- The customer information is printed using scaffold.
- We create here a Export button and when it click it generate the Excel.
- The view screen look like below;
Create Export Post method to convert the data into Excel
As we already discuss we are not using any 3rd party libraries to export excel, here we can simply GridView control of the System.Web.UI.WebControls namespace that is part of ASP.NET Web Form and it do conversion of MS Excel following below steps.
- On Export() we fetch the data from customer list.
- Using help of GridView control of the System.Web.UI.WebControls namespace append the customer data into Gridview.
- Rendering the GridView conent using HtmlTextWriter and StringWriter.
Everything is okay now, so let’s run the application and see the output like below;
You can see like above image we do code for export data into excel format in ASP.NET MVC without using any 3rd part library, we just use the Grid-view Controls that are present in System.Web.UI.WebControls.
So far this article we discuss how to export the data into MS Excel in ASP .NET MVC without using any 3rd party libraries. If have any suggestion about this article please give your feedback.