Tuesday 7 August 2012

"Report Generate in Excel/Word/PDF in asp.net using c#"


default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" CellPadding="4" AutoGenerateColumns="False"
            EnableModelValidation="True" ForeColor="#333333" GridLines="None"
            Width="1000px" onrowediting="GridView1_RowEditing" >
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:TemplateField HeaderText="AddressLine1">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("AddressLine1") %>'></asp:TextBox>
                       
                     
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("AddressLine1") %>'></asp:Label>
                       

                    </ItemTemplate>
                    <ItemStyle Width="10%" />
                </asp:TemplateField>
               
                <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="25%" >

<ItemStyle Width="25%"></ItemStyle>

                </asp:BoundField>
                <asp:BoundField DataField="PostalCode" HeaderText="PostalCode"
                    ItemStyle-Width="25%" >

<ItemStyle Width="25%"></ItemStyle>

                </asp:BoundField>
                <asp:BoundField DataField="rowguid" HeaderText="rowguid" ItemStyle-Width="10%" >

<ItemStyle Width="10%"></ItemStyle>

                </asp:BoundField>
                <asp:CommandField ShowEditButton="True" />
            </Columns>
            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
        </asp:GridView>

        <br />
        <asp:Button ID="btnReport" runat="server" Text="Export"
            onclick="btnReport_Click" />
       

    </div>
    </form>
</body>
</html>


default.aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
       
       SqlConnection conn = new SqlConnection(@"Data Source=SP2010;Initial Catalog=AdventureWorks;Integrated Security=True");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Mfill();
            }
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            Mfill();
        }

        private void Mfill()
        {
            SqlCommand cmd = new SqlCommand("select top 10 AddressLine1,City,PostalCode,rowguid from Person.Address", conn);

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
            Session["Beneficiary_Report"] = ds;
        }

        protected void btnReport_Click(object sender, EventArgs e)
        {
            Export_Data();
        }

        protected void Export_Data()
        {
            try
            {
                if (GridView1.Rows.Count < 1)
                {
                    ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", @"alert('Unable to Find Information to Export');", true);
                    return;
                }
                string ls_item_list = null;
                //first let's clean up the response.object
                Response.Clear();
                Response.Charset = "";
                //set the response mime type for excel
               Response.ContentType = "application/vnd.ms-Excel";
                //Response.ContentType = "application/pdf";
                //Response.ContentType = "application/msword";  // for word
             
                Response.Clear();

                //create a string writer
                System.IO.StringWriter stringWrite = new System.IO.StringWriter();
                //create an htmltextwriter which uses the stringwriter
                System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
                //instantiate a datagrid
                DataGrid dg = new DataGrid();
                DataSet ds1 = null;
                dg.ItemStyle.Font.Size = FontUnit.Medium;
                dg.HeaderStyle.ForeColor = System.Drawing.Color.Black;
                dg.HeaderStyle.Font.Bold = true;
                dg.HeaderStyle.Font.Size = FontUnit.Point(10);
                dg.HeaderStyle.BackColor = System.Drawing.Color.Gray;
               // ds1 = new DataSet();  // for this row print same to same page in excel.

//ds1 = (DataSet)Session["Beneficiary_Report"];   // both are work below use method to return a object 
                ds1 = (DataSet)ReturnSessionVariable("Beneficiary_Report");
                dg.DataSource = ds1.Tables[0];
                dg.DataBind();
                dg.RenderControl(htmlWrite);
                Response.Write(stringWrite.ToString());
                Response.End();
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", @"alert('Unable to Export Informtion Pleae Try again');", true);
            }

        }

        private object ReturnSessionVariable(string key)
        {
            return Session[key];
            //else
            //{
            //    Session["Error_Type"] = EnumErrors.BadRequest;
            //    Response.Redirect("invaliduser.aspx");
            //}
        }

    }
}




No comments:

Post a Comment