Click here to Skip to main content
15,898,999 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
I want to export a gridview data with image to an Excel document.

When I executed following code, GridView data was exported to Excel
properly. But no image was displayed in Excel. Only a blank image icon
was show inside Excel.


Could any body point out what is wrong in my code or missing anything?

Thanks,

------------------------- Code Start ----------------------------------------------
protected void Button1_Click(object sender, System.EventArgs e)
{
	ExportGridToExcel(GridView1, "mydata.xls");
}
public void ExportGridToExcel(GridView grdGridView, string fileName)
{
	Response.Clear();
	Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
	Response.Charset = "";
	Response.ContentType = "application/vnd.xls";

	StringWriter stringWrite = new StringWriter();
	HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
	grdGridView.RenderControl(htmlWrite);
	Response.Write(stringWrite.ToString());
	Response.End();
}



public override void VerifyRenderingInServerForm(Control control)
{
}

-----------------------------------

I am Show Data in Grid like this

-----------------------------------

public void GetData()
{

	DataSet ds = new DataSet();

	System.Data.SqlClient.SqlDataAdapter da = null;

	string strSQL = null;



	strSQL = Session("StrQuery");

	string connString = dpath;

	da = new System.Data.SqlClient.SqlDataAdapter(strSQL, connString);

	if (!Page.IsPostBack()) {
		da.Fill(ds);
		ds = null;
		ds = new DataSet();
	}

	da.Fill(ds);
	ds.Tables[0].Columns.Add("imgFile");




	foreach (DataRow tempRow in ds.Tables[0].Rows) {
		tempRow["imgFile"] = ("ReadRealImage.aspx?ID=" + tempRow["ID"]);

	}


	GridView1.DataSource = ds.Tables[0].DefaultView;
	GridView1.DataBind();

	
}
----------------------------------------
ReadRealImage.aspx
----------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Data.SqlClient.SqlDataReader;
using System.IO;
partial class Admin_ReadRealImage : System.Web.UI.Page
{
	protected void Page_Load(object sender, System.EventArgs e)
	{
		string dpath = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString2").ConnectionString;




		try {
			DataSet ds = new DataSet();

			System.Data.SqlClient.SqlDataAdapter da = null;

			byte[] arrContent = null;

			DataRow dr = null;

			string strSql = null;



			strSql = "SELECT MembersIDCardData.ID,MembersIDCardData.Picture, MembersIDCardData.ImgTitle, MembersIDCardData.imgType, MembersIDCardData.imaLength FROM MembersIDCardData Where MembersIDCardData.ID=" + Request.QueryString["ID"];



			string connString = dpath;

			da = new System.Data.SqlClient.SqlDataAdapter(strSql, connString);

			da.Fill(ds);

			dr = ds.Tables[0].Rows[0];

			arrContent = Convert.ToByte(dr["Picture"]);

			string conType = dr["imgType"].ToString();

			Response.ContentType = conType;

			Response.OutputStream.Write(arrContent, 0, dr["imaLength"]);

			Response.End();


		} catch (Exception ex) {


		}





	}
	public Admin_ReadRealImage()
	{
		Load += Page_Load;
	}

}



[Edited]Code is wrapped in "pre" tag[/Edited]
Posted
Updated 15-Oct-11 20:48pm
v2

convert your image data in bmp format.
 
Share this answer
 
You need to provide the absolute URL to excel.
Have a look here[^] - this should give you an idea on what you need to do.
 
Share this answer
 
/*----------------------------------------------*/
//Author : Mudassar Khan
//Article: Export GridView with Images to Word, Excel and PDF Formats
//WebSite: http://www.aspsnippets.com
/*----------------------------------------------*/


using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string strQuery = "select * from tblFiles order by ID";
SqlCommand cmd = new SqlCommand(strQuery);
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
protected void Export_Grid(object sender, EventArgs e)
{
Button btn = (Button)sender;
switch (btn.CommandArgument)
{
case "Word":
Word_Export();
break;
case "Excel":
Excel_Export();
break;
case "PDF":
PDF_Export();
break;
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
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 = @" .textmode { mso-number-format:\@; } ";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
C#
protected string GetUrl(string imagepath)
   {
       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 + imagepath;
       }
       return imagepath;
   }
 
Share this answer
 
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string strQuery = "select * from tblFiles order by ID";
SqlCommand cmd = new SqlCommand(strQuery);
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
protected void Export_Grid(object sender, EventArgs e)
{
Button btn = (Button)sender;
switch (btn.CommandArgument)
{
case "Word":
Word_Export();
break;
case "Excel":
Excel_Export();
break;
case "PDF":
PDF_Export();
break;
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
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 = @" .textmode { mso-number-format:\@; } ";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
C#
protected string GetUrl(string imagepath)
   {
       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 + imagepath;
       }
       return imagepath;
   }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900