Guruji Point - Code You Want To Write

  • Home
  • Asp.Net
  • WCF
  • SQL
  • Type Script
  • AngularJS
  • Tech News
  • Blog
  • Earn Online

Sunday, 29 May 2016

Export GridView Data In Excel And Word File

 No comments   

Introduction

In this article i will explain you how to export (Download) all Grid data in Excel and Word doc file. 

Description

Here i repeat the same process as i did my previous updates to bind Grid-View. 

Database Design

Create Database EmployeeDb
Use EmployeeDb

Create table Employee( Id int Identity(1,1), Name varchar(50),EmailId nvarchar(250), Address varchar(max) , MobileNo int )

Aspx page View

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
  
        <form id="form1" runat="server"> 
        <div> <br /> <br /> 
              <asp:GridView ID="gvUserInfo" runat="server"  AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333">
                <Columns>
                    <asp:BoundField DataField="Name" HeaderText="Name"  ItemStyle-Width="150px" />
                    <asp:BoundField DataField="EmailID" HeaderText="Email Id" ItemStyle-Width="150px"  />
                    <asp:BoundField DataField="Address" HeaderText="Address" ItemStyle-Width="140px" />
                    <asp:BoundField DataField="MobileNo" HeaderText="Mobile No" ItemStyle-Width="140px" />
                </Columns>
                   <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            </asp:GridView>
            <asp:Button ID="btnExport" runat="server" OnClick="btnExport_Click" Text="Export To Excel" /> </div> <br /> <br/>
                     </form>
</body>
</html>

After completing the design phase go to view code window and write the code given  below
CS page View 

   public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered*/
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    //method for Displaying Data in Gridview 
    protected void BindGrid()
    {
        SqlConnection con = new SqlConnection("Data Source=JP-PC\\JP;Initial            Catalog=EmployeeDb;Integrated Security=true;");
        SqlCommand cmd = new SqlCommand("SELECT * FROM Employee", con);
        con.Open();
        DataSet ds = new DataSet();
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.Fill(ds);
        gvUserInfo.DataSource = ds;
        gvUserInfo.DataBind();
        con.Close();

    }
  
    protected void btnExport_Click(object sender, EventArgs e)
    {

        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Users.doc"));
        Response.ContentType = "application/ms-word";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        gvUserInfo.AllowPaging = false;
        gvUserInfo.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();

    }

 In above code you can see i used a VerifyRenderingInServerForm function. The purpose of this function is avoid the error like "control must be placed in inside of form tag". If we set VerifyRenderingInServerForm function then compiler will think that controls rendered before exporting and our functionality will work perfectly.
If you are not using this function on your page then your localhost gives you error "control must be placed in inside of form tag".

Export Excel File from Grid


After successfully exporting Grid to Word Doc you can also export it to Excel File by using following code.

protected void btnExport_Click(object sender, EventArgs e)
    {

        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Users.xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        gvUserInfo.AllowPaging = false;
        gvUserInfo.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();

    }

Use the same code i used in Word file exporting ,only required changes in Export functionality.
For to clear understanding about outputs refer the below screen-shots.




  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

Facebook Updates

Guruji Point

Categories

Comman table Expression in SQL Dynamic Grid Row IQueryable in c# Learn AngularJS Scope_Identity() Use of indexes comma seperated string in sql row_number() and dense_rank() salary table structure. while loop in sql why do we need cursor why tuple used

About Us

This blog is about the Programming ,Tech News and some intresting facts related Contents. Here you can find fundamental and expert level topic of programming languages very practically related to C# , Asp.Net ,Sql-Server, JavaScript, Jquery, WebServices And also Web-Api, WCF ,WPF, Angular Js.

Contact Us

Email Us - gurujipoints@gmail.com
Contact- 8077657477

Reach Us

Copyright © Guruji Point - Code You Want To Write