简体   繁体   中英

Exporting GridView to Excel exports the whole page

I am exporting a GridView to an Excel file, but when I open the file, first I get an error regarding the fact that the format type and extension don't match, and when I open it the whole page is brought into the Excel file, not just the grid view.

I'm not using an Update Panel. I tried with the button inside the GridView and outside and the same result, so it seems it might be something from the code-behind which looks like this:

  Response.Clear(); Response.Buffer = true; string filename = "GridViewExport_" + DateTime.Now.ToString() + ".xls"; Response.AddHeader("content-disposition", "attachment;filename=" + filename); Response.Charset = String.Empty; Response.ContentType = "application/vnd.ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); GridView3.RenderControl(hw); //style to format numbers to string string style = @"<style> .textmode { mso-number-format:\\@; } </style>"; Response.Write(style); Response.Output.Write(sw.ToString()); Response.Flush(); HttpContext.Current.ApplicationInstance.CompleteRequest(); 

You can try this method:

void ExportDataSetToExcel(GridView grdData, string filename)
{
    grdData.BorderStyle = BorderStyle.Solid;
    grdData.BorderWidth = 1;
    grdData.BackColor = Color.WhiteSmoke;
    grdData.GridLines = GridLines.Both;
    grdData.Font.Name = "Verdana";
    grdData.Font.Size = FontUnit.XXSmall;
    grdData.HeaderStyle.BackColor = Color.DimGray;
    grdData.HeaderStyle.ForeColor = Color.White;
    grdData.RowStyle.HorizontalAlign = HorizontalAlign.Left;
    grdData.RowStyle.VerticalAlign = VerticalAlign.Top;

    HttpResponse response = HttpContext.Current.Response;
    response.Clear();
    response.Charset = "";
    response.ContentType = "application/vnd.ms-excel";
    response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename+ "\"");

    using (var sw = new StringWriter())
    {
        using (var htw = new HtmlTextWriter(sw))
        {
            grdData.RenderControl(htw);
            response.Write(sw.ToString());
            response.End();
        }
    }
}

USE this code: This will work fine..

aspx code::

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="default.aspx.cs" Debug ="true" enableEventValidation ="false" Inherits="default"%>

Here is the aspx code :

  protected void ConvertToExcel_Click(object sender, EventArgs e)     
  {
    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Report.xls"));
    Response.ContentType = "application/ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();

    GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");

    for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
    {
        GridView1.HeaderRow.Cells[i].Style.Add("background-color", "#bfc2c7");
    }
    int j = 1;

    foreach (GridViewRow gvrow in GridView1.Rows)
    {

        if (j <= GridView1.Rows.Count)
        {
            if (j % 2 != 0)
            {
                for (int k = 0; k < gvrow.Cells.Count; k++)
                {
                    gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
                }
            }
        }
        j++;
    }
    GridView1.RenderControl(htw);
    Response.Write(sw.ToString());
    Response.End();


}

public override void VerifyRenderingInServerForm(Control control)
{

}

Solved !!! your code is correct only problem with Response.Flush(); using in the code instead of Response.Flush(); you should use Response.End();

Below is the working code:

        Response.Clear();

        Response.Buffer = true;
        string filename = "GridViewExport_" + DateTime.Now.ToString() + ".xls";
        Response.AddHeader("content-disposition",
        "attachment;filename=" + filename);
        Response.Charset = String.Empty;
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);


        GridView3.RenderControl(hw);
        //style to format numbers to string
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.End();
       // Response.Flush();
        HttpContext.Current.ApplicationInstance.CompleteRequest();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM