www.kevincornwell.com
.NET DataGrid (or GridView) To Excel Utility
    protected void Button3_Click(object sender, EventArgs e)
    {
 
 
        DataSet dsExport = dataSet;
        DataGrid dgExport = new DataGrid();
        dgExport.DataSource = dsExport;
 
        //ExportToExcel();
 
        DataGridToExcel(dgExport, Response);
    }
 
    protected void DataGridToExcel(DataGrid dGridExport, HttpResponse httpResp)
    {
        httpResp.Clear();
        httpResp.Charset = "";
        httpResp.ContentType = "application/vnd.ms-excel";
        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        DataGrid dGrid = new DataGrid();
        dGrid = dGridExport;
        dGrid.HeaderStyle.Font.Bold = true;
        dGrid.DataBind();
        dGrid.RenderControl(htmlWrite);
        httpResp.Write(stringWrite.ToString());
        httpResp.End();
    }

Or to export a DataGrid to Excel use:

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        exportToExcel();
    }
 
    protected void exportToExcel()
    {
        VerifyRenderingInServerForm(GridView1);
 
        /* This is a limit in Excel prior to Office 2007 */
        if (GridView1.Rows.Count > 65536)
        {
            Page.Response.Clear();
            Page.Response.Write("Too many lines to export.");
            Page.Response.End();
        }
        GridView1.AllowPaging = false;
        GridView1.AllowSorting = false;
        GridView1.DataBind();
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
        Response.Charset = "";
        // If you want the option to open the Excel file without saving than
        // comment out the line below
        // Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
    }
 
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }

Comments RSS


Leave a comment:


Blog | Contact | Gallery | Links | Google Latitude (location) | Music | Sandbox | Search | SharePoint | Social Networking | Software | Weather | Web Design


Copyright © 1997-2009 KCSH. All rights reserved.