Friday, 21 July 2017

Export in database data to excel in MVC

For xlsx formart

Install-package EPPlus from manage nugget package. It writes Excel 2007/2010 files using the Open Office Xml format (xlsx) only.



var data = (from a in db.Tables select a).ToList();
            ExcelPackage excel = new ExcelPackage();
            var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
   //workSheet.Cells[1, 1].LoadFromDataTable(myDataTable, true);
            workSheet.Cells[1, 1].LoadFromCollection(data, true);
            using (var memoryStream = new MemoryStream())
            {
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;  filename=Contact.xlsx");
                excel.SaveAs(memoryStream);
                memoryStream.WriteTo(Response.OutputStream);
                Response.Flush();
                Response.End();
            }


For xls formart

 For xls formart no need to add any package .


var data = (from a in db.Tables select a).ToList();
            var grid = new System.Web.UI.WebControls.GridView();
            grid.DataSource = data;
            grid.DataBind();
            Response.Clear();
            Response.Buffer = true;
            Response.ClearContent();
            Response.ClearHeaders();
            Response.Charset = "";         
            StringWriter strwritter = new StringWriter();
            HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", "attachment;filename=FileName.xls");         
            grid.RenderControl(htmltextwrtter);
            Response.Write(strwritter.ToString());
            Response.End();



No comments:

Post a Comment