Friday 5 December 2014

export gridview to excel in asp.net c#

public void ExportGridviewToExcel(GridView gvnmae, string strFileName)
    {
        try
        {
            HttpContext context = HttpContext.Current;
            string strText = "";

            context.Response.Clear();
            context.Response.Buffer = true;
            context.Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + ".csv");
            context.Response.Charset = "";
            context.Response.ContentType = "application/text";

            StringBuilder sb = new StringBuilder();
            for (int k = 0; k <= gv.HeaderRow.Cells.Count - 1; k++)
            {
                if (gv.HeaderRow.Cells[k].Visible == true & gv.HeaderRow.Cells[k].CssClass != "hiddenColumn")
                {
                    //add separator
                    sb.Append(gv.HeaderRow.Cells[k].Text + ',');
                }
            }
            //append new line          
            sb.Append(System.Environment.NewLine);
            for (int i = 0; i <= gv.Rows.Count - 1; i++)
            {
                for (int k = 0; k <= gv.Rows[i].Cells.Count - 1; k++)
                {
                    if (gv.Rows[i].Cells[k].Visible == true & gv.Rows[i].Cells[k].CssClass != "hiddenColumn")
                    {
                        //add separator

                        strText = "";
                        strText = (gv.Rows[i].Cells[k].Text.Contains(",") ? "\"" + gv.Rows[i].Cells[k].Text + "\"" : gv.Rows[i].Cells[k].Text);
                        strText = strText.Replace("&nbsp;", "");

                        //sb.Append(gv.Rows(i).Cells(k).Text + ","c)
                        sb.Append(strText + ',');
                    }
                }
                //append new line
                sb.Append(System.Environment.NewLine);
            }
            context.Response.Output.Write(sb.ToString());
            context.Response.Flush();
            context.Response.End();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

No comments:

Post a Comment