In this article I will explain with an example, how to export Grid (Html Table) data from database to CSV (Text) file in ASP.Net MVC Razor.
First the Grid (Html Table) will be populated from database using Entity Framework and then the records from the database will be exported and downloaded as Microsoft CSV (Text) file in ASP.Net MVC Razor.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Configuring and connecting Entity Framework to database
Now I will explain the steps to configure and add Entity Framework and also how to connect it with the database.
You will need to add Entity Data Model to your project by right clicking the Solution Explorer and then click on Add and then New Item option of the Context Menu.
From the Add New Item window, select ADO.NET Entity Data Model and set its Name as NorthwindModel and then click Add.
Then the Entity Data Model Wizard will open up where you need to select EF Designer database option.
Now the wizard will ask you to connect and configure the Connection String to the database.
You will need to select the
1. SQL Server Instance
2. Database
And then click Test Connection to make sure all settings are correct.
Once the Connection String is generated, click Next button to move to the next step.
Next you will need to choose the Entity Framework version to be used for connection.
Now you will need to choose the Tables you need to connect and work with Entity Framework. Here Customers Table is selected.
The above was the last step and you should now have the Entity Data Model ready with the Customers Table of the Northwind Database.
Namespaces
You will need to import the following namespaces.
using System.Linq;
using System.Text;
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, the Top 10 Customer records are fetched and returned to the View.
Action method for handling the CSV (Text) file Export and Download operation
This Action method is executed when the Export Submit button is clicked.
Note: The following Action method performs File Download and hence the return type is set to FileResult.
The Top 10 Customer records are fetched from the Customers Table using Entity Framework.
Then a loop is executed over the records fetched using Entity Framework and a comma separated (delimited) string is generated which is ultimately converted to a Byte Array.
Finally the Byte Array is exported and downloaded as CSV (Text) file using the File function.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
NorthwindEntities entities = new NorthwindEntities();
return View(from customer in entities.Customers.Take(10)
select customer);
}
[HttpPost]
public FileResult Export()
{
string[] columnNames = new string[] { "CustomerId", "ContactName", "City", "Country" };
NorthwindEntities entities = new NorthwindEntities();
var customers = from customer in entities.Customers.Take(10)
select customer;
//Build the CSV file data as a Comma separated string.
string csv = string.Empty;
foreach (string columnName in columnNames)
{
//Add the Header row for CSV file.
csv += columnName + ',';
}
//Add new line.
csv += "\r\n";
foreach (var customer in customers)
{
//Add the Data rows.
csv += customer.CustomerID.Replace(",", ";") + ',';
csv += customer.ContactName.Replace(",", ";") + ',';
csv += customer.City.Replace(",", ";") + ',';
csv += customer.Country.Replace(",", ";") + ',';
//Add new line.
csv += "\r\n";
}
//Download the CSV file.
byte[] bytes = Encoding.ASCII.GetBytes(csv);
return File(bytes, "application/text", "Grid.csv");
}
}
View
Now you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.
The Name of the View is set to Index, the Template option is set to Empty, the Model class is set to Customer Entity (the one we have generated using Entity Framework) and finally the Data context class is set to NorthwindEntities.
Inside the View, in the very first line the Customer Entity is declared as IEnumerable which specifies that it will be available as a Collection.
For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
Finally there’s an HTML Submit button enclosed inside a Form with the Action method specified as Export.
When this Button will be clicked, the Grid (Html Table) data will be exported and downloaded as CSV (Text) file.
@model IEnumerable<Export_Excel_MVC.Customer>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<h4>Customers</h4>
<hr/>
<table cellpadding="0" cellspacing="0">
<tr>
<th>CustomerID</th>
<th>Contact Name</th>
<th>City</th>
<th>Country</th>
</tr>
@foreach (Customer customer in Model)
{
<tr>
<td>@customer.CustomerID</td>
<td>@customer.ContactName</td>
<td>@customer.City</td>
<td>@customer.Country</td>
</tr>
}
</table>
<br/>
<br/>
@using (Html.BeginForm("Export", "Home", FormMethod.Post))
{
<input type="submit" value="Export"/>
}
</body>
</html>
Screenshots
Grid (Html Table)
Exported CSV (Text) file
Downloads