Monday, 27 April 2015

Export excel using C# gridview

Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=ExpiredList.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            using (StringWriter sw = new StringWriter())
            {
                HtmlTextWriter hw = new HtmlTextWriter(sw);

                //To Export all pages
                grvExpiredList.AllowPaging = false;
                if (grvExpiredList.Columns.Count == 8)
                {
                    grvExpiredList.Columns[7].Visible = false;
                    grvExpiredList.Columns[6].Visible = false;
                }
                this.LoadExpiredData();

                grvExpiredList.HeaderRow.BackColor = Color.White;
                foreach (TableCell cell in grvExpiredList.HeaderRow.Cells)
                {
                    cell.BackColor = grvExpiredList.HeaderStyle.BackColor;
                }
                foreach (GridViewRow row in grvExpiredList.Rows)
                {
                    row.BackColor = Color.White;
                    foreach (TableCell cell in row.Cells)
                    {
                        if (row.RowIndex % 2 == 0)
                        {
                            cell.BackColor = grvExpiredList.AlternatingRowStyle.BackColor;
                        }
                        else
                        {
                            cell.BackColor = grvExpiredList.RowStyle.BackColor;
                        }
                        cell.CssClass = "textmode";
                    }
                }

                grvExpiredList.RenderControl(hw);

                //style to format numbers to string
                string style = @"<style> .textmode { mso-number-format:\@; } </style>";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();

No comments:

Post a Comment