Search code examples
c#asp.netexcelgridview

Export Gridview to excel with Images


in my web page , i have a gridview with data and some images, Here i want to export gridview to excel with Images,I'm trying with below code, it export data only, here how can i export to excel with images ?

 Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
    Response.ContentType = "application/ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    GridView1.HeaderRow.Style.Add("background-color", "Red");
    for (int i = 0; i < GridView1.Columns.Count - 2; i++)
    {
        GridView1.HeaderRow.Cells[i].Style.Add("background-color", "Red");
    }
    GridView1.RenderControl(htw);
    Response.Write(sw.ToString());
    Response.End();

here i am using Openoffice calc to read excel files


Solution

  • replace function code with this

    private void Excel_Export()
        {
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
     "attachment;filename=GridViewExport.xls");
    Response.Charset = "";
    
    Response.ContentType = "application/vnd.ms-excel";
    
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        GridViewRow row = GridView1.Rows[i];
    
        //Apply text style to each Row
        row.Attributes.Add("class", "textmode");
    }
    
    GridView1.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();
    Response.End();
    }
    

    Refer this link for more details