i want to export in excel file when click on web page a tag. please help me.

this is my datatable:

            DataTable dt = new DataTable("Student");
            dt.Columns.Add("StudentId", typeof(Int32));
            dt.Columns.Add("StudentName", typeof(string));
            dt.Columns.Add("Address", typeof(string));
            dt.Columns.Add("MobileNo", typeof(string));
            //Data 
            dt.Rows.Add(1, "Abishek", "Hyderabad", "0000000000");
            dt.Rows.Add(2, "Pawan", "Hyderabad", "111111111");
            dt.Rows.Add(3, "Namit", "Pune", "1222222222");
            dt.Rows.Add(4, "Neha", "Bhagalpur", "3333333333");

1 Answers

  1. Aditya Kumar Patel
    export datatable to excel file in asp.net mvc arya mercy
    8/29/2018 10:05:04 AM

    Try to use it:

     

    Write the following code on the razor page:


    @Html.ActionLink("Export To Excel", "ExportToExcel","Home")

     

    Write the following code in the controller:

     

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.UI;
    using System.Web.UI.WebControls;
     
    namespace SQLTutorialsPointMVC.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
     
            public ActionResult ExportToExcel()
            {
                DataTable dt = new DataTable("Student");
                dt.Columns.Add("StudentId", typeof(Int32));
                dt.Columns.Add("StudentName", typeof(string));
                dt.Columns.Add("Address", typeof(string));
                dt.Columns.Add("MobileNo", typeof(string));
                //Data 
                dt.Rows.Add(1, "Abishek", "Hyderabad", "0000000000");
                dt.Rows.Add(2, "Pawan", "Hyderabad", "111111111");
                dt.Rows.Add(3, "Namit", "Pune", "1222222222");
                dt.Rows.Add(4, "Neha", "Bhagalpur", "3333333333");
     
                Response.Clear();
                Response.ClearContent();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=ExcelFile.xls");
     
                //Create a dynamic control, populate and render it
                GridView excel = new GridView();
                excel.DataSource = dt;
                excel.DataBind();
                excel.RenderControl(new HtmlTextWriter(Response.Output));
                Response.Flush();
                Response.End();
                return null;
            }
            
        }
    }




Leave a answer

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like