How To Download SQL Records In Excel Format Using MVC

Today, in this article, I will explain how to download records in Excel format from database. If we are downloading an Excel file from one table, then we can download in an easy way. But suppose, we have to download from more than one table; or we have to download to different sheets in an Excel file; or if we have some already-existing format in an Excel file and we just  have to update the fields in sheets; then it's very difficult. However, now I have a solution.

Here, I have used 3 tables with no relationship among them. Here, I'm downloading the first table in sheet1 and the first and second table are downloading sheet 2. I will use MVC with SQL Server.

Step1

First, let's create 3 tables in the database.

Step2

Now, we have to add the tables in my MVC application. I have used Entity Framework with LINQ query.

For that, I created an MVC  application and went through, File->New ->Web application ->select MVC ->OK.

Go to Model folder ->Right click -> Add -> New item -> ADO.NET Entity Data Model -> click Add -> select database first approch->Click Next.

Select New Connection and give the connection details, then select database ->Click OK.
Choose tables and click OK.



Step3

First, we have to display records for understanding purpose. So for that I am using partial view to display records of 3 tables in separately in one page

For this, I added a controller in Controller folder after that I created 3 PartialView methods like these BookDetails(),CourseDetails() and TeacherDetails()

->So, see in brief, How to create partial view, For that write partial method and give the return type PartialViewResult and write the code for fetching the records form database like below



So finally I wrote all three tables' logic for fetching the records from database 

  1. //for fetching the book details  
  2.         public PartialViewResult BookDetails()  
  3.         {  
  4.             var bookDetails=new List<BookDetail>();  
  5.             using (MKDBEntities DBContext = new MKDBEntities())  
  6.             {  
  7.                 bookDetails = DBContext.BookDetails.ToList();  
  8.             }  
  9.             return PartialView(bookDetails);  
  10.         }  
  11.   
  12. //for fetching the course details  
  13.         public PartialViewResult CourseDetails()  
  14.         {  
  15.             var courseDetails = new List<Course>();  
  16.             using (MKDBEntities DBContext = new MKDBEntities())  
  17.             {  
  18.                 courseDetails = DBContext.Courses.ToList();  
  19.   
  20.             }  
  21.             return PartialView(courseDetails);  
  22.   
  23.         }  
  24.   
  25. //for fetching the teachers details  
  26.         public PartialViewResult TeacherDetails()  
  27.         {  
  28.             var teacherDetails = new List<Teacher>();  
  29.         
  30.             using (MKDBEntities DBContext = new MKDBEntities())  
  31.             {  
  32.                 teacherDetails = DBContext.Teachers.ToList();  
  33.             }  
  34.             return PartialView(teacherDetails);  
  35.         }   

->Now I am creating view to display of the partial view one by one so for that just right and select partial view in check box, like this



Next click add button and write view code 

  1. @model IEnumerable<ExcelFileDownload.Models.BookDetail>  
  2. <table class="table" style="border:2px solid">  
  3.     <tr class="btn-primary">  
  4.         <th>Order Number</th>  
  5.         <th>Author</th>  
  6.         <th>Publisher</th>  
  7.         <th>Price</th>  
  8.   
  9.     </tr>  
  10.     @foreach (var item in Model)  
  11.     {  
  12.         
  13.         <tr class="btn-info">  
  14.   
  15.             <td>@item.BookName</td>  
  16.             <td>@item.Author</td>  
  17.             <td>@item.Publisher</td>  
  18.             <td>@item.Price</td>  
  19.         </tr>  
  20.   
  21.     }  
  22. </table>   

So similarly I created 2 more partial views for course details and teacher details

CourseDetails.cshtml 

  1. @model IEnumerable<ExcelFileDownload.Models.Course>  
  2.   
  3. <table class="table" style="border:2px solid">  
  4.     <tr class="btn-danger">  
  5.         <th>Course Name</th>  
  6.         <th>Location</th>  
  7.   
  8.     </tr>  
  9.     @foreach (var item in Model)  
  10.     {  
  11.   
  12.         <tr class="btn-warning">  
  13.   
  14.             <td>@item.CourseName</td>  
  15.             <td>@item.Location</td>  
  16.         </tr>  
  17.   
  18.     }  
  19. </table>   

TeachersDetails.cshtml 

  1. @model IEnumerable<ExcelFileDownload.Models.Teacher>  
  2.   
  3. <table class="table" style="border:2px solid">  
  4.     <tr class="btn-success">  
  5.         <th>Teacher Name</th>  
  6.         <th>Teacher Type</th>  
  7.   
  8.     </tr>  
  9.   @foreach (var item in Model)  
  10.   {  
  11.   
  12.         <tr class="btn-primary">  
  13.   
  14.             <td>@item.TeacherName</td>  
  15.             <td>@item.TeacherType</td>  
  16.         </tr>  
  17.   
  18.     }  
  19. </table>   

Now we can see the output below but before that we have to create a view page for calling all 3 partial views 

  1. public ActionResult Index()  
  2.         {  
  3.             return View();  
  4.         }   

Now we've added a view page and called 3 partial views 

  1. @{  
  2.     ViewBag.Title = "Index";  
  3.   
  4. }  
  5.   
  6. <h2>All Details</h2>  
  7. <div>  
  8. @using (Ajax.BeginForm("DownloadExcel""Demo"new AjaxOptions { HttpMethod = "POST" }))  
  9. {  
  10.     
  11.         Html.RenderAction("BookDetails");  
  12.         Html.RenderAction("CourseDetails");  
  13.         Html.RenderAction("TeacherDetails");  
  14.       
  15.     <input type="submit" value="Download In Excel" />  
  16.         }  
  17. </div>   

Now we can see the output



Step4

Now when I click the download button all the records should be downloaded in excel format so again remember here I am downloading bookdetails in sheet1 and course details and teacher details in sheet2 in Excel file

Here I gave an Excel file for default format in DetailFormatInExcel folder.



So for that I created a separate class in models folder and I gave the name BussinessLayer and wrote all logic to create excel format one by one. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace ExcelFileDownload.Models  
  8. {  
  9.     public class BusinessLayer  
  10.     {  
  11.         public DataTable GetXlsTableCourse()  
  12.         {  
  13.             var dt = new DataTable();  
  14.             dt.Columns.Add(new DataColumn  
  15.             {  
  16.                 AllowDBNull = false,  
  17.                 AutoIncrement = true,  
  18.                 AutoIncrementSeed = 1,  
  19.                 ColumnName = "Course Name",  
  20.                 DataType = typeof(string)  
  21.             });  
  22.             dt.Columns.Add(new DataColumn  
  23.             {  
  24.                 AllowDBNull = true,  
  25.                 ColumnName = "Location",  
  26.                 DataType = typeof(string)  
  27.             });  
  28.   
  29.   
  30.   
  31.             return LoadTableData(dt);  
  32.         }  
  33.        
  34.         public DataTable LoadTableData(DataTable dt)  
  35.         {  
  36.             var courseDetails = new List<Course>();  
  37.             MKDBEntities DBContext = new MKDBEntities();  
  38.   
  39.             courseDetails = DBContext.Courses.ToList();  
  40.   
  41.   
  42.             foreach (var item in courseDetails)  
  43.             {  
  44.                 var dr = dt.NewRow();  
  45.   
  46.                 dr["Course Name"] = item.CourseName;  
  47.                 dr["Location"] = item.Location;  
  48.                 dt.Rows.Add(dr);  
  49.                 dt.AcceptChanges();  
  50.             }  
  51.             return dt;  
  52.         }  
  53.         public DataTable GetXlsTableTeacher()  
  54.         {  
  55.             var dt = new DataTable();  
  56.   
  57.             dt.Columns.Add(new DataColumn  
  58.             {  
  59.                 AllowDBNull = true,  
  60.                 ColumnName = "Teacher Name",  
  61.                 DataType = typeof(string)  
  62.             });  
  63.             dt.Columns.Add(new DataColumn  
  64.             {  
  65.                 AllowDBNull = true,  
  66.                 ColumnName = "Teacher Type",  
  67.                 DataType = typeof(string)  
  68.             });  
  69.             return LoadTableDataDetails(dt);  
  70.         }  
  71.         public DataTable LoadTableDataDetails(DataTable dt)  
  72.         {  
  73.             var teacherDetails = new List<Teacher>();  
  74.             MKDBEntities DBContext = new MKDBEntities();  
  75.   
  76.             teacherDetails = DBContext.Teachers.ToList();  
  77.   
  78.   
  79.             foreach (var item in teacherDetails)  
  80.             {  
  81.                 var dr = dt.NewRow();  
  82.   
  83.                 dr["Teacher Name"] = item.TeacherName;  
  84.                 dr["Teacher Type"] = item.TeacherType;  
  85.                 dt.Rows.Add(dr);  
  86.                 dt.AcceptChanges();  
  87.             }  
  88.             return dt;  
  89.         }  
  90.         public DataTable GetXlsTableBooks()  
  91.         {  
  92.             var dt = new DataTable();  
  93.   
  94.             dt.Columns.Add(new DataColumn  
  95.             {  
  96.                 AllowDBNull = true,  
  97.                 ColumnName = "BookName",  
  98.                 DataType = typeof(string)  
  99.             });  
  100.             dt.Columns.Add(new DataColumn  
  101.             {  
  102.                 AllowDBNull = true,  
  103.                 ColumnName = "Author",  
  104.                 DataType = typeof(string)  
  105.             });  
  106.             dt.Columns.Add(new DataColumn  
  107.             {  
  108.                 AllowDBNull = true,  
  109.                 ColumnName = "Publisher",  
  110.                 DataType = typeof(string)  
  111.             });  
  112.             dt.Columns.Add(new DataColumn  
  113.             {  
  114.                 AllowDBNull = true,  
  115.                 ColumnName = "Price",  
  116.                 DataType = typeof(string)  
  117.             });  
  118.             return LoadTableBookDetails(dt);  
  119.         }  
  120.         public DataTable LoadTableBookDetails(DataTable dt)  
  121.         {  
  122.             var bookDetails = new List<BookDetail>();  
  123.             MKDBEntities DBContext = new MKDBEntities();  
  124.   
  125.             bookDetails = DBContext.BookDetails.ToList();  
  126.   
  127.   
  128.             foreach (var item in bookDetails)  
  129.             {  
  130.                 var dr = dt.NewRow();  
  131.   
  132.                 dr["BookName"] = item.BookName;  
  133.                 dr["Author"] = item.Author;  
  134.                 dr["Publisher"] = item.Publisher;  
  135.                 dr["Price"] = item.Price;  
  136.                 dt.Rows.Add(dr);  
  137.                 dt.AcceptChanges();  
  138.             }  
  139.             return dt;  
  140.         }  
  141.     }  
  142. }   

Now I created a method in controller and I gave the name DownloadExcel()

  1. public ActionResult DownloadExcel()  
  2.         {  
  3.   
  4.             BusinessLayer BAL = new BusinessLayer();  
  5.             var workbook = new Spire.Xls.Workbook();  
  6.   
  7.             workbook.LoadFromFile(Server.MapPath("~/DetailFormatInExcel/DetailsFormat.xlsx"));  
  8.             var worksheet1 = workbook.Worksheets[0];  
  9.             var worksheet2 = workbook.Worksheets[1];  
  10.             byte[] array = null;  
  11.             var dt1 = BAL.GetXlsTableBooks();  
  12.             worksheet1.InsertDataTable(dt1, false, 3, 1);  
  13.             var dt2 = BAL.GetXlsTableCourse();  
  14.             worksheet2.InsertDataTable(dt2, false, 3, 1);  
  15.             var dt3 = BAL.GetXlsTableTeacher();  
  16.             worksheet2.InsertDataTable(dt3, false, 3, 3);  
  17.             
  18.             using (var ms = new System.IO.MemoryStream())  
  19.             {  
  20.                 workbook.SaveToStream(ms, FileFormat.Version2010);  
  21.                 ms.Seek(0, System.IO.SeekOrigin.Begin);  
  22.                 array = ms.ToArray();  
  23.             }  
  24.   
  25.             return File(array, "application / vnd.openxmlformats - officedocument.spreadsheetml.sheet"," Detail.xlsx");  
  26.         }   

Now I have completed coding part

So finally we can download the excel file

This is sheet1 result for bookdetails



This is sheet2 result for course details and teacher details



Thanks and happy coding