In this article, I will show you how to export imageto excel file in asp.net c#.
The user can upload image using fileuploadcontrol and it will be displayed using Image control. We can set image to imagecontrol by converting the relative url to absolute url. Then Dynamically createa table and add image and finally export the table to excel.
Design pageImageToExcel.aspx:
<form id="form1" runat="server">
<div style="border: 1px solid #357ae8; padding:15px 15px 15px 15px ; width: 350px; height: 350px">
<asp:Image ID="Image1" ImageUrl="~/Uploads/grade.jpg" runat="server" Height="300" Width="350" />
<br />
<br />
<asp:Button ID="Button1" Text="Export" OnClick="ExportExcel" runat="server" />
</div>
</form>
Code behindImageToExcel.aspx.cs:
protected void ExportExcel(object sender, EventArgs e)
{
//Convert the Relative Url toAbsolute 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 = new Table();
//Add Image control to the TableCell.
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 toResponse.
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;
}
protected void Upload_image(object sender, EventArgs e)
{
string fileName = FileUpload1.FileName;
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + fileName));
Image1.ImageUrl = "~/Uploads/" + FileUpload1.FileName;
}
Ouput:
image exported to the excel sheet: