First Snap Shot: Hi everyone. This is my first article on MVC. In this small article we can learn how to download the Excel format file in MVC. I have used the Razor Engine in this article. We know that MVC has no server control, so how can we do this?
Note: In the MVC Razor engine we use HTML 5. The Razor engine has no server controls like a Button, Radio Button, Grid View and so on. If you want more details about HTML5 then try this link.
Note: In the MVC Razor engine we use HTML 5. The Razor engine has no server controls like a Button, Radio Button, Grid View and so on. If you want more details about HTML5 then try this link.
Road Map:
- Design
- SQL Data
- jQuery snippet code
- jQuery complete code
- Model
- Controller
- Details of Controller
- Business Logic Layer
- Data Access layer
- Create Stored Procedure
- Get data using Stored Procedure
Design
- <input type="text" id="EmployeeName" title="Employee Name" />
- <br />
- <input type="text" id="Age" title="AGE" />
- <br />
- <input type="text" id="Address" title="Address" />
- <br />
- <a id="btnDownloadFile" href="#">Down Load File </a>
- <br/>
You can check the preceding code. This is a HTML control, it has no runat="server" and also has no server-side click. This HTML control works with the lovely and smart jQuery. This is a link type control and I have it set in the HREF # because I don't want it to redirect to another page.
Note: Suppose I want a file downloaded based on some condition. I know you might be confused, don't worry, I will explain more of what I want.
Note: Suppose I want a file downloaded based on some condition. I know you might be confused, don't worry, I will explain more of what I want.
I have one Employees data as in the following.
SQL Data
SQL Data
- SrNo. Employee Age City
- 1 Jogi 23 Noida
- 2 Vimal 40 Delhi
- 3 Naveen 24 Gurgoan
I want only the data with the Employee Name "Jogi" or the age is greater then 23. So I need the three TextBoxes for Employee Name, Age and City. I pass some condition to get the data based on a condition.
jQuery snippet code here
If have no server control then you must use another resource so here I used jQuery. Without jQuery and Ajax I have no idea how to do this. I created a simple function to download the Excel format file.
I have created some code for downloading the Excel format file. How to working check out line by line.
- $('#btnExportToExcel').click(function () {
- var employeename = null;
- var age= null;
- var address=null;
- if($('#txtemployeename').val()!='')
- {
- employeename=$('#txtemployeename').val();
- }
Here we check whether the text box is empty. If the Text box is not empty then pass the value otherwise pass the null value. I checked every value one by one. I placed every code.
- $.ajax({
- type: "GET",
Note: Without Ajax we have no option available to get or post the data. Ajax is a true developer's friend because it solves many problems. Ajax is part of various things, if you want more about ajax then check on Google. Try this link for more information about ajax. Type: "Get" is an action of a page.
Any page has two states one is "GET" and the other is "Post". Here we used the GET type.
- url: '@Url.Action("Method Name", "Controller Name")',
- async: false,
- data: {EmployeeName: employeename,Age:age,Address:address},
- data: {
- EmployeeName: employeename,
- Age=age,
- Address:address
- }
- if (d.success) { // d.success is return type of Boolean. If d.success is true then download your file otherwise pop message "NO Records file"
- window.location = '/Project/DownloadExcelReport?fName=' + d.fileName;
- }
- else alert('No records found');
- $('#btnExportToExcel').click(function () {
- var employeename = null;
- var age= null;
- var address=null;
- if($('#txtemployeename').val()!='')
- {
- employeename=txtemployeename;
- }
- if($('#txtage').val()!='')
- {
- age=txtage;
- }
- if($('#txtaddress').val()!='')
- {
- address=txtaddress;
- }
- $.ajax({
- type: "GET",
- url: '@Url.Action("DownLoadProjectProposal", "Project")',
- async: false,
- data: {EmployeeName: employeename,Age:age,Address:address},
- datatype: "JSONP",
- contentType: "application/json; charset=utf-8",
- success: function (d) {
- if (d.success) {
- window.location = '/Project/DownloadExcelReport?fName=' + d.fileName;
- }
- else alert('No records found');
- }
- });
- });
- });
Model
In the model we defined the properties in the Export class. In the class are a couple of properties, like EmployeeName, Age and Address.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace Export
- {
- public class ExportTOExcel
- {
- public string EmployeeName { get; set; }
- public int Age { get; set; }
- public string Address { get; set; }
- }
- }
Controller
- public ActionResult ExportToExcel(string EmployeeName,int Age,string Address )
- {
- objExport ObjEx=new ObjExport();
- string fileName = string.Empty;
- bool success = false;
-
- try
- {
- if ((EmployeeName!='' || EmployeeName!=null) || Age>0 ||(Address !='' ||Address!=null)
- {
- StringBuilder str = new StringBuilder();
- var lstCompany = ObjEx.GetExportToExcel(EmployeeName,Age,Address);
- if (lstCompany.Count() > 0)
- {
- str.Append("<table border=`" + "1px" + "`b>");
- str.Append("<tr>");
-
- str.Append("<td><b><font face=Arial Narrow size=3>EmployeeName</font></b></td>");
- str.Append("<td><b><font face=Arial Narrow size=3>Age</font></b></td>");
- str.Append("<td><b><font face=Arial Narrow size=3>Address</font></b></td>");
- str.Append("</tr>");
- foreach (var val in lstCompany)
- {
- str.Append("<tr>");
- str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.EmloyeeName+ "</font></td>");
- str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.Age + "</font></td>");
- str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.Address+ "</font></td>");
- str.Append("</tr>");
- }
- str.Append("</table>");
- fileName = "Employee.xls";
- success = true;
- TempData["myExcel"] = str.ToString();
- TempData.Keep("myExcel");
- }
- }
- return Json(new { success = success, fileName }, JsonRequestBehavior.AllowGet);
- }
- catch
- {
- throw;
- }
- objExport ObjEx=new ObjExport(); // crate reference for business logic function.
- if ((EmployeeName!='' || EmployeeName!=null) || Age>0 ||(Address !='' ||Address!=null) //condition
- // true when any parameters have value.
- var lstCompany = ObjEx.GetExportToExcel(EmployeeName,Age,Address);
- if (lstCompany.Count() > 0) //lcheck here stCompany have data or not. if lstCompany.count
- //is greater then means have data otherwise false this condition.
- //create a header for excel file.
- str.Append("<td><b><font face=Arial Narrow size=3>EmployeeName</font></b></td>");
- str.Append("<td><b><font face=Arial Narrow size=3>Age</font></b></td>");
- str.Append("<td><b><font face=Arial Narrow size=3>Address</font></b></td>");
Business Logic Layer
- Public List<ExportTOExcel > GetExportToExcel(string EmployeeName,int Age, string Address)
- {
- List<ExportTOExcel> LstExportFile=null;
- DLExport DL= new DLExport();
- LstExportFile=DL.GetExportToExcel(EmployeeName,Age,Address);
- return LstExportFile;
- }
- Public List<ExportTOExcel > GetExportToExcel(string EmployeeName,int Age, string Address)
- {
- List<ExportTOExcel> LstExportFile=null;
-
- try
- {
- using (CGRS_OGEntities dbContext = new CGRS_OGEntities())
- {
- IEnumerable<ExportToExcel> IExportFile = (from T in dbContext.TableName
- where T.EmployeeName.Contains(EmployeeName) OR T.Age.contains(Age) or T.Address.contains(Address)
- select new ExportTOExcel
- {
- EmployeeName= T.EmployeeName,
- Age= T.Age,
- Address=T.Address
-
- LstExportFile= IExportFile.ToList<ExportTOExcel>();
-
- return LstExportFile;
- }
- finally
- { }
- }
Create Stored Procedure
- Create Store Procedure GetDataExport
- (
- @EmployeeName varchar(max),
- @Age int,
- @address varchar(max)
- )
- as
- begin
- SET NOCOUNT ON
- select Employee,Age,Address from TableName T --Note:-You can use the *(Star), but due to performance issue we avoid this.
- where T.Employee=@EmployeeName and T.Age=@Age and T.Address=@Address
- end
- SET NOCOUNT ON --Set Nocount On it's return null value. No overhead Sql count how many records effect.
- -- So try always if no count really need this.
Get data using Stored Procedure
- Public List<ExportTOExcel > GetExportToExcelUsingProcedure(string EmployeeName,int Age, string Address)
- {
- List<ExportTOExcel> LstExportFile=null;
- try
- {
- using (CGRS_OGEntities dbContext = new CGRS_OGEntities())
- {
- LstExportFile = dbContext.GetDataExport(EmployeeName,Age,Address).ToList<ExportTOExcel>();
-
- }
- return LstExportFile;
- }
- finally
- { }
- }
Final Words
I hope it's helpful for everyone to export data in Excel format. If you have an issue regarding this article or code please drop your comments in the comment box.

Gowtham RajamanickamPosted Apr 25, 2015, 6:08 AM
this is great
Gowtham RajamanickamPosted Apr 25, 2015, 6:08 AM
good
Joginder BangerPosted Apr 10, 2015, 1:34 PM
I forgot one simple actionresult public ActionResult DownloadExcelReport(string fName) { byte[] contents = null; try { if (TempData["myExcel"] != null) { contents = System.Text.Encoding.UTF8.GetBytes(TempData["myExcel"].ToString()); } else { contents = System.Text.Encoding.UTF8.GetBytes(" "); } return File(contents, "application/vnd.ms-excel", fName); } catch (Exception ex) { throw ex; } finally { } }
Joginder BangerPosted Apr 10, 2015, 1:33 PM
Thanks every one for your kind word..
Manish Kumar ChoudharyPosted Apr 10, 2015, 7:35 AM
nICE ONE.
DhanasekarPosted Apr 10, 2015, 3:04 AM
Nice article
Sibeesh VenuPosted Apr 10, 2015, 1:37 AM
Good one.
NitinPosted Apr 10, 2015, 1:11 AM
nice
Santhakumar MunuswamyPosted Apr 9, 2015, 11:32 PM
Good work