Friday 9 January 2015

Gridview To Excel In C# & VB.NET

Gridview To Excel In C# & VB.NET:

C#

private void Excel_Export()

{

    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);

    GridView1.AllowPaging = false;

    GridView1.DataBind();

    for (int i = 0; i < GridView1.Rows.Count; i++)

    {

        GridViewRow row = GridView1.Rows[i];

        //Apply text style to each Row

        row.Attributes.Add("class", "textmode");

    }

    GridView1.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();

}

   
                 

VB.Net



Private Sub Excel_Export()

   Response.Clear()

   Response.Buffer = True

   Response.AddHeader("content-disposition", _

    "attachment;filename=GridViewExport.xls")

   Response.Charset = ""

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

   Dim sw As New StringWriter()

   Dim hw As New HtmlTextWriter(sw)

   GridView1.AllowPaging = False

   GridView1.DataBind()

   For i As Integer = 0 To GridView1.Rows.Count - 1

     Dim row As GridViewRow = GridView1.Rows(i)

    'Apply text style to each Row

     row.Attributes.Add("class", "textmode")

   Next

   GridView1.RenderControl(hw)



   'style to format numbers to string

   Dim style As String = "<style> .textmode " _

     & "{ mso-number-format:\@; } </style>"

   Response.Write(style)

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

   Response.Flush()

   Response.End()

End Sub

 Finally the method that one should not forget is the below otherwise the GridView export will throw the Error

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.



C#.Net

public override void VerifyRenderingInServerForm(Control control)

{

    /* Verifies that the control is rendered */

}

VB.Net

Public Overloads Overrides Sub VerifyRenderingInServerForm(

ByVal control As Control)

        ' Verifies that the control is rendered

End Sub
 

No comments:

Post a Comment