C#

Friday, February 21, 2014

Export Asp.net Grid view Data In to CSV File: Using Asp.net, C#, Entity Data Model

Step 1:

Create a data Base Table in SQL Server 2008:
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Employee](
      [Id] [int] IDENTITY(1,1) NOT NULL,
      [EmployeeName] [nvarchar](30) NULL,
      [Salary] [decimal](7, 2) NULL,
PRIMARY KEY CLUSTERED
(
      [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Step 2:

In Visual Studio Create a Project Some Name(Ex:TestProject)
In Visual Studio Add New Ado.net Entity data Model Give the Wizard data and Add Employee Table to Model

Step 3:

In Visual Studio Add Web Form Name Some Test.aspx
Write code in Test.aspx:
<div>
                <br />
                <asp:Label ID="lblMessage" runat="server" Font-Bold="true" />
                <br />
                <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="false">
                    <EmptyDataTemplate>
                        <div style="padding: 10px;">
                            No Data Found!</div>
                    </EmptyDataTemplate>
                    <Columns>
                        <asp:BoundField HeaderText="Id" DataField="Id" />
                        <asp:BoundField HeaderText="EmployeeName" DataField="EmployeeName" />
                        <asp:BoundField HeaderText="Salary" DataField="Salary" />                      
                    </Columns>
                </asp:GridView>
                <br />
                <asp:Button ID="btnExportToCSV" runat="server" Text="Export Data to CSV" OnClick="btnExportToCSV_Click" />
            </div>

Step 4:

In Code Behind Means Test.aspx.cs:
Page Load:
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                populateData();
                lblMessage.Text = "Current Database Data.";
            }
        }
Implement Code For populateData()

private void populateData()
        {
            using (TestEntities dc = new TestEntities())
            {
                gvData.DataSource = dc.Employees.ToList();
                gvData.DataBind();
            }
        }
Write Code For ExportToCsv Button Click Event:
        protected void btnExportToCSV_Click(object sender, EventArgs e)
        {
            List<Employee> emList = new List<Employee>();
            using (TestEntities dc = new TestEntities())
            {
                emList = dc.Employees.ToList();
            }

            if (emList.Count > 0)
            {
                string header = @"""Id"",""EmployeeName"",""Salary""";
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(header);

                foreach (var i in emList)
                {
                    sb.AppendLine(string.Join(",",
                        string.Format(@"""{0}""", i.Id),
                        string.Format(@"""{0}""", i.EmployeeName),
                        string.Format(@"""{0}""", i.Salary)));                     
                }

                // Download Here

                HttpContext context = HttpContext.Current;
                context.Response.Write(sb.ToString());
                context.Response.ContentType = "text/csv";
                context.Response.AddHeader("Content-Disposition", "attachment; filename=EmployeeData.csv");
                context.Response.End();
            }          
        }

 Note:I tested Several Times Working Perfect If Any Queries Post Below.Thankyou..

1 comment:

  1. Casino Hotel Tunica - JTH Hub
    Hotel 경상남도 출장마사지 - See 939 traveler reviews, 62 부천 출장샵 photos, and 순천 출장안마 great deals for Casino Hotel Tunica, ranked #3 among luxury hotels in Tunica. 부산광역 출장샵 Rating: 3 · ‎939 광양 출장안마 reviews

    ReplyDelete