Monday, June 6, 2022

Grid View export to Excel ASP.NET C# with hiding of columns

 protected void ExportToExcel(object sender, EventArgs e)

    {

        Response.Clear();

        Response.Buffer = true;

        Response.AddHeader("content-disposition", "attachment;filename=CourseList.xls");

        Response.Charset = "";

        Response.ContentType = "application/vnd.ms-excel";

        using (StringWriter sw = new StringWriter())

        {

            HtmlTextWriter hw = new HtmlTextWriter(sw);


            //To Export all pages

            grdCourseMaster.AllowPaging = false;

            BindGrid();


            grdCourseMaster.HeaderRow.BackColor = Color.White;

            foreach (TableCell cell in grdCourseMaster.HeaderRow.Cells)

            {

                cell.BackColor = grdCourseMaster.HeaderStyle.BackColor;

            }

            foreach (GridViewRow row in grdCourseMaster.Rows)

            {

                row.BackColor = Color.White;

                foreach (TableCell cell in row.Cells)

                {

                    if (row.RowIndex % 2 == 0)

                    {

                        cell.BackColor = grdCourseMaster.AlternatingRowStyle.BackColor;

                    }

                    else

                    {

                        cell.BackColor = grdCourseMaster.RowStyle.BackColor;

                    }

                    cell.CssClass = "textmode";

                }

            }


            grdCourseMaster.Columns[6].Visible = false;

            grdCourseMaster.Columns[7].Visible = false;

            grdCourseMaster.Columns[8].Visible = false;



            grdCourseMaster.RenderControl(hw);


            //style to format numbers to string

            string style = @"<style> .textmode { } </style>";

            Response.Write(style);

            Response.Output.Write(sw.ToString());

            Response.Flush();

            Response.End();

        }

    }


    public override void VerifyRenderingInServerForm(Control control)

    {

        /* Verifies that the control is rendered */

    }

No comments:

Post a Comment