Thursday, 20 March 2014

export datagridview to excel c#

Exporting the data from gridview to excel sheet; most of the time for report purpose we need to get the data into excel sheet. It gives the data into tabular view into excel sheet;


  @Code Snippet to export data into excel sheet in c#

private void ExportDatetoExcel()
    {
        //Forming datagrid
        DataGrid Dg = new DataGrid();
        Dg.HeaderStyle.Font.Bold = true;
        Dg.HeaderStyle.ForeColor = Color.Blue;
        Dg.DataSource = GetCustomerObject(); //binding customer object
        Dg.DataBind();
        //creating the response object
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.ms-excel";
        string fileName = "CustomerReports.xls";
        Response.AddHeader("Content-Disposition", "FileName=" + fileName);
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.Charset = "";
        EnableViewState = false;
        StringWriter oStringWriter = new StringWriter();
        HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
        Dg.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString()); // wring the data
        Dg.Dispose();
        Response.End();
    }

1 comment:

  1. You can import GridView data to excel in c# using Aspose.Cells for .NET API also. It allows you to import data from many other sources also into excel using C#/.NET. To view complete list of data sources from where you can import data to excel and their sample codes in C#, Check out their documentation page.

    http://www.aspose.com/docs/display/cellsnet/Importing%20Data%20to%20Worksheets

    ReplyDelete