export image to excel in axp.net


Description:-

In this example we will see how to export image to excel file using asp.net. here I have created sample demo example to export image to excel.

Default.aspx:-

<div>
  <asp:Image ID="Image1" ImageUrl="~/Files/U1-icon.jpg" runat="server" Height="300" Width="350"/>
  <br/>
  <br/>
  <asp:Button ID="Button1" Text="Export" OnClick="ExportExcel" runat="server"/>
</div>

Default.aspx.cs:-

protected void ExportExcel(object sender, EventArgs e)
{
  //Convert the Relative Url to Absolute Url and set it to Image control.
  Image1.ImageUrl = this.GetAbsoluteUrl(Image1.ImageUrl);

  using (StringWriter sw = new StringWriter())
  {
    using (HtmlTextWriter hw = new HtmlTextWriter(sw))
    {
      //Create a Table.
      Table table = newTable();

      //Add Image control to the Table Cell.
      TableRow row = new TableRow();
      row.Cells.Add(new TableCell());
      row.Cells[0].Controls.Add(Image1);
      table.Rows.Add(row);

      //Render the Table as HTML.
      table.RenderControl(hw);

      //Export the Table to Excel.
      Response.Clear();
      Response.Buffer = true;
      Response.AddHeader("content-disposition", "attachment;filename=Images.xls");
      Response.Charset = "";
      Response.ContentType = "application/vnd.ms-excel";

      //Write the HTML string to Response.
      Response.Write(sw.ToString());
      Response.Flush();
      Response.End();
    }
  }
}

private string GetAbsoluteUrl(string relativeUrl)
{
  relativeUrl = relativeUrl.Replace("~/", string.Empty);
  string[] splits = Request.Url.AbsoluteUri.Split('/');
  if (splits.Length >= 2)
  {
    string url = splits[0] + "//";
    for (int i = 2; i < splits.Length - 1; i++)
    {
      url += splits[i];
      url += "/";
    }

    return url + relativeUrl;
  }
  return relativeUrl;
}

public override void VerifyRenderingInServerForm(Control control)
{
  /* Verifies that the control is rendered */
}

Related Posts

Previous
Next Post »

Thanks for comments.....