mavera
mavera

Reputation: 3241

Export Page which include images to Excel

I have page which contains 2 gridview and 2 mschart. ı want to export this page to excel. For this purpose I took these controls into a panel and write this code:

    Response.Clear();        
    Response.ContentType = "application/vnd.msexcel";
    Response.AddHeader("content-disposition", "attachment; filename=rapor.xls");
    Response.ContentEncoding = System.Text.Encoding.Default;
    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    panel1.RenderControl(htmlWrite);
    Response.Write(stringWrite.ToString());
    Response.End();

When this code run, everything is ok except charts. They aren't coming to excel. How can I do it?

Upvotes: 1

Views: 3205

Answers (2)

Arun Singh
Arun Singh

Reputation: 1546

Try the following code. I have tested at local IIS, it is working properly and including the image like Header Image/Logo on top of the grid data. you have to include your chart as images.

Response.ContentType = "application/vnd.ms-excel";        
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");                
StringWriter stringWrite = new StringWriter();        
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);        
dgrExport.DataSource = dtExport;        
dgrExport.DataBind();
dgrExport.RenderControl(htmlWrite);
string headerTable = @"<Table><tr><td><img src=""D:\\Folder\\1.jpg"" \></td></tr></Table>";
Response.Write(headerTable);
Response.Write(stringWrite.ToString());        
Response.End();

you can adjust your image's height and width as per your requirement. Same height and width setting will be required for the <TD> tag.

Upvotes: 0

Eduardo Molteni
Eduardo Molteni

Reputation: 39443

Not 100% sure, but I guess that the charts are written to memory to display on the page, so they vanish after the request.

HTML does not allow an image to be embedded in the code, you have to reference a external file.

Options:

  1. Check if the chart allow the image to be written to disk, but beware of the large number of temp files that you may have to store so the excel reports keep showing the image
  2. (Recomended) Export the report to PDF.

Upvotes: 1

Related Questions