Sunday 21 July 2013

EXPORT MULTIPLE GRIDVIEWS TO EXCEL SHEET ON SINGLE BUTTON CLICK(Code Behind)

The code given below is for getting custom output in excel sheet.
In this example 12 Gridviews are used and are arranged in a custom format in excel sheet...

Browser Output



        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;

            Response.AddHeader("content-disposition",
             "attachment;filename=GridViewExport.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            Table tb = new Table();
         

            TableRow tr1 = new TableRow();
            TableCell cell1 = new TableCell();
            cell1.Controls.Add(GridView1);
            tr1.Cells.Add(cell1);
            TableCell cell2 = new TableCell();
            cell2.Controls.Add(GridView2);
            tr1.Cells.Add(cell2);
            TableCell cell3 = new TableCell();
            cell3.Controls.Add(GridView3);
            tr1.Cells.Add(cell3);
            TableCell cell4 = new TableCell();
            cell4.Controls.Add(GridView4);
            tr1.Cells.Add(cell4);
            TableCell cell5 = new TableCell();
            cell5.Controls.Add(GridView5);
            tr1.Cells.Add(cell5);
            TableCell cell6 = new TableCell();
            cell6.Controls.Add(GridView6);
            tr1.Cells.Add(cell6);
            tb.Rows.Add(tr1);
               
      ////////////////////////Second row on Excel Sheet/////////////////////////

            TableRow tr2 = new TableRow();
            TableCell cell7 = new TableCell();
            cell7.Controls.Add(GridView7);
            tr2.Cells.Add(cell7);
            TableCell cell8 = new TableCell();
            cell8.Controls.Add(GridView8);
            tr2.Cells.Add(cell8);
            TableCell cell9 = new TableCell();
            cell9.Controls.Add(GridView9);
            tr2.Cells.Add(cell9);
            TableCell cell10 = new TableCell();
            cell10.Controls.Add(GridView10);
            tr2.Cells.Add(cell10);
            TableCell cell11 = new TableCell();
            cell11.Controls.Add(GridView11);
            tr2.Cells.Add(cell11);
            TableCell cell12 = new TableCell();
            cell12.Controls.Add(GridView12);
            tr2.Cells.Add(cell12);
            tb.Rows.Add(tr2);

            tb.RenderControl(hw);

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

        }

Excel output

 If you find any problem with the code,be free to comment below...
We will try to solve it....

0 comments:

Post a Comment