Export Data From Database Table to Excel File in ASP.Net MVC

Export data from database table to Excel is a frequently required feature in web and window application, there are many ways to upload data from a database to Excel and here I'm going to show one simple common method to export.

To start this task you need to create a database for storing data in a data table that exports an Excel file.

The design of the database table looks like the following.

database table

First of all open Visual Studio 2012 then select "New project" and click on ASP.NET MVC4 Web Application in Visual C#. Name the project ExportToExcel or whatever you like. Create a controller named ExportToExcelController and in this controller create an ActionResult method named Index. Here I select data from the database for display on index view:
  1. Public ActionResult Index()    
  2. {    
  3.     String constring = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;    
  4.     SqlConnection con = newSqlConnection(constring);    
  5.     string query = "select * From Person";    
  6.     DataTabledt = newDataTable();    
  7.     con.Open();    
  8.     SqlDataAdapter da = newSqlDataAdapter(query, con);    
  9.     da.Fill(dt);    
  10.     Con.Close();    
  11.     IList<ExportToExcelModel> model = newList<ExportToExcelModel>();    
  12.     for (int i = 0; i <dt.Rows.Count; i++)    
  13.     {    
  14.         model.Add(newExportToExcelModel()    
  15.         {    
  16.              Id = Convert.ToInt32(dt.Rows[i]["Id"]),    
  17.              Name = dt.Rows[i]["Name"].ToString(),    
  18.              Email = dt.Rows[i]["Email"].ToString(),    
  19.              Mobile = dt.Rows[i]["Mobile"].ToString(),    
  20.         });    
  21.     }    
  22.     return View(model);    
  23. }

Now create a view, right-click on the Indexaction method and select Add View and then click OK. Write the following code to the view for displaying the data.

  1. namespace ExportToExcel.Models    
  2. {    
  3.     public class ExportToExcelModel    
  4.     {    
  5.         public int Id { getset; }    
  6.         public string Name { getset; }    
  7.         public string Email { getset; }    
  8.         public string Mobile { getset; }    
  9.     }    
  10. } 

Now create a view, right-click on the Indexaction method and select Add View and then click OK. Write the following code for the view for displaying data.

  1. @model IEnumerable<ExportToExcel.Models.ExportToExcelModel>  
  2. @{  
  3. ViewBag.Title = "Index";  
  4. }  
  5. <h2>Index</h2>  
  6. <p>  
  7. <ahref="ExportToExcel"class="m-btn red">Export To Excel</a>  
  8. </p>  
  9. <table>  
  10. <tr>  
  11. <th>@Html.DisplayNameFor(model =>model.Name)</th>  
  12. <th>@Html.DisplayNameFor(model =>model.Email)</th>  
  13. <th>@Html.DisplayNameFor(model =>model.Mobile)</th>  
  14. <th></th>  
  15. </tr>  
  16. @foreach (var item in Model) {  
  17. <tr>  
  18. <td>@Html.DisplayFor(modelItem =>item.Name)</td>  
  19. <td>@Html.DisplayFor(modelItem =>item.Email)</td>  
  20. <td>@Html.DisplayFor(modelItem =>item.Mobile)</td>  
  21. </tr>  
  22. }  
  23. </table>  

Now create another actionmethod”ExportToExcel()” for exporting data from the data table. Here I am using Microsoft's “Microsoft.Office.Interop.Excel” library (for this your system must contain Microsoft Office 2007) for converting the data into Excel form. You can add this library by right-clicking on References. Now click on Add Reference, now click on extension in the Assembly tab now select Microsoft.Office.Interop.Excel.

  1. public Action ResultExportToExcel()  
  2. {  
  3.     int i = 0;  
  4.     int j = 0;  
  5.     string sql = null;  
  6.     string data = null;  
  7.     Excel.Application xlApp;  
  8.     Excel.Workbook xlWorkBook;  
  9.     Excel.Worksheet xlWorkSheet;  
  10.     object misValue = System.Reflection.Missing.Value;  
  11.     xlApp = new Excel.Application();  
  12.     xlApp.Visible = false;  
  13.     xlWorkBook = (Excel.Workbook)(xlApp.Workbooks.Add(Missing.Value));  
  14.     xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet;  
  15.     string conn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;  
  16.     SqlConnection con = newSqlConnection(conn);  
  17.     con.Open();  
  18.     var cmd = newSqlCommand("SELECT TOP 0 * FROM Person", con);  
  19.     var reader = cmd.ExecuteReader();  
  20.     int k = 0;  
  21.     for (i = 0; i <reader.FieldCount; i++)  
  22.     {  
  23.         data = (reader.GetName(i));  
  24.         xlWorkSheet.Cells[1, k + 1] = data;  
  25.         k++;  
  26.     }  
  27.     char lastColumn = (char)(65 + reader.FieldCount - 1);  
  28.     xlWorkSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;  
  29.     xlWorkSheet.get_Range("A1", lastColumn + "1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;  
  30.     reader.Close();  
  31.     sql = "SELECT * FROM Person";  
  32.     SqlDataAdapter dscmd = newSqlDataAdapter(sql, con);  
  33.     DataSet ds = newDataSet();  
  34.     dscmd.Fill(ds);  
  35.     for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)  
  36.     {  
  37.         var newj = 0;  
  38.         for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)  
  39.         {  
  40.             data = ds.Tables[0].Rows[i].ItemArray[j].ToString();  
  41.            xlWorkSheet.Cells[i + 2, newj + 1] = data;  
  42.            newj++;  
  43.         }  
  44.     }  
  45.     xlWorkBook.Close(true, misValue, misValue);  
  46.     xlApp.Quit();  
  47.     release Object(xlWorkSheet);  
  48.     release Object(xlWorkBook);  
  49.     release Object(xlApp);  
  50.     return RedirectToAction("Index""ExportToExcel");  
  51. }  
  52. private void releaseObject(object obj)  
  53. {  
  54.     try  
  55.     {  
  56.          System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);  
  57.          obj = null;  
  58.    }  
  59.    catch  
  60.    {  
  61.        obj = null;  
  62.         //MessageBox.Show("Exception Occured while releasing object " + ex.ToString());  
  63.    }  
  64.    finally  
  65.    {  
  66.        GC.Collect();  
  67.    }  
  68. }  

Now build and run your application.

run your application
This is your Index page with Export to Excel link. Now click on the Export To Excel link and export the data as a .xls file. The Excel file will look like.
 
Export to Excel

If you have any issues and queries then feel free to contact me.