Monday, January 16, 2023

Generate Excel Bulk Report in Asp.Net With Extension method

To Generate the faster report for bulk data i used following code base for the download the data. Sample Code is :-

Supporting DLL is Click here (ClosedXML.dll)

 if (dtBase != null && dtBase.Rows.Count > 0)
        {
            if (dtBase.Rows.Count > 0)
            {
                dtBase.ExportExcel("VKYC_Report", "VKYC_Report");
            }
            else
            {
                lblError.Text = "Records not found.";
            }
        }
        else
        {
            lblError.Text = "Records not found.";
        }
-------------------------

public static class Extension
{
    public static void ExportExcel(this DataTable dt, string WorksheetName = "Report", string FileName = "Report")
    {
        try
        {
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dt, WorksheetName);
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.Buffer = true;
                    HttpContext.Current.Response.Charset = "";
                    HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".xlsx");
                    using (MemoryStream MyMemoryStream = new MemoryStream())
                    {
                        wb.SaveAs(MyMemoryStream);
                        MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
                        HttpContext.Current.Response.Flush();
                        HttpContext.Current.Response.End();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // throw;
        }
    }
}

No comments:

Post a Comment