Export Data through Excel sheet in Asp.net Mvc

How to Export Excel sheet with data using Asp.net.

1> Create a table UploadFile for an example

    CREATE TABLE [dbo].[UploadFile] (
    [Id]         INT           IDENTITY (1, 1) NOT NULL,
    [CategoryId] INT           NOT NULL,
    [TypeId]     INT           NOT NULL,
    [Path]       VARCHAR (MAX) NOT NULL,
    [Status]     BIT           NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

2> Insert the dummy data , so that it will help to visible data properly.

3> Now Create a Model name it  UploadFile.cs  and Map with table (UploadFile)  using Table Attribute.


4> Configure or map the model (UploadFile )with Dbset  in   DefaultConnection. class ,
so that we can fetch the data from table.   


5> To view the existing data from database to  in the index  , so we right the code in side the Index Action  :

var model = def.uploadfile.ToList();

6> Create view for index. Add view  right click on Index Action -> select template ->List ->
      select model class-> choose layout --> View ->share ->_Layout.cshtml



7> Run the Project -->uploadfile will list with  data .
8> Now create Action for ExportData() , so that we can write the logic for export excel in controller.

   Add :- def.uploadfileContext.ToList() to Data Source.
  ex:-     gv.DataSource = def.uploadfileContext.ToList();
  


  public ActionResult ExportData()
        {
            GridView gv = new GridView();
            gv.DataSource = def.uploadfileContext.ToList();  <---------- Add here.
            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename= '" +                                                                                                                            System.DateTime.Now.TimeOfDay + "'.xls");
            Response.ContentType = "application/ms-excel";
            Response.Charset = "";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();

            return RedirectToAction("Index");
        }

9> Now we have to  add the button for Export to Excel using Post method.

@using (Html.BeginForm("ExportData", "UploadFile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="submit" name="Export" id="Export" value="Download" class="btn  btn-hover btn-primary   icon-download pull-right" />
}





10>Run the Project : Button will Appear and click to export to excel. 


11> Download and Open


12> All data exported according to table contain the data.


Thank You.....


Share this

Previous
Next Post »