ASP.NET Excel Function

This function written in c# builds a MS excel out of a dataSet.

    private DataSet dataSet = new DataSet();
    private DataView dView = new DataView();
 
    private void LoadPeople()
    {
        SqlConnection conn = new SqlConnection("Data Source=asdf;User ID=asdf;Password=asdf;Database=Directory");
        SqlDataAdapter dAdapter = new SqlDataAdapter("SELECT * FROM People", conn);
        dAdapter.Fill(dataSet, "peeps");
        dView.Table = dataSet.Tables["peeps"];
        personel_cnt = dView.Count;
        dView.Table.Columns.Add("is_a_member");
        conn.Close();
    }
 
    private void buildExcelReport()
    {
        DataSet dsExport = dataSet;
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw =
           new System.Web.UI.HtmlTextWriter(tw);
        DataGrid dgGrid = new DataGrid();
        dgGrid.DataSource = dsExport;
 
        //Report Header
        hw.WriteLine("My Super Duper Excel Report");
        hw.WriteLine("<br>∓nbsp;");
        // Get the HTML for the control.
        dgGrid.HeaderStyle.Font.Bold = true;
        dgGrid.DataBind();
        dgGrid.RenderControl(hw);
 
        // Write the HTML back to the browser.
        Response.ContentType = "application/vnd.ms-excel";
        this.EnableViewState = false;
        Response.Write(tw.ToString());
        Response.End();
    }

1 Comment(s)

Micheal Rike (August 23, 2007 2:08 am)

Good code to export data, I used Spire.XLS,
It’s easy to use yet.

Comments RSS


Leave a comment:


Blog | Contact | Gallery | Links | Sandbox | Social Networking | Weather | Web Design


Copyright © 1997-2009 KCSH. All rights reserved.