如何从Gridview将图像导出到Excel [英] How to export image to Excel from Gridview

查看:132
本文介绍了如何从Gridview将图像导出到Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我想将带有图像的gridview数据导出到Excel文档.

当我执行以下代码时,GridView数据已导出到Excel
适当地.但是在Excel中没有显示图像.仅有空白图片图标
在Excel中显示.


任何人都可以指出我的代码出了什么问题或遗漏了什么吗?

谢谢,

-------------------------代码开始----------------------- -----------------------

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)
{
}


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

我正在像这样在Grid中显示数据

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

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]代码包装在"pre"标签中[/Edited]

解决方案

将图像数据转换为bmp格式.

您需要提供excel的绝对URL.
在此处中查看 [ ^ ]-这应该使您对需要执行的操作有所了解.


/* ----- ----------------------------------------- */
//作者:Mudassar Khan
//文章:将带有图像的GridView导出为Word,Excel和PDF格式
//网站:http://www.aspsnippets.com
/* ---------------------------------------------- */


使用系统;
使用System.Data;
使用System.Data.SqlClient;
使用System.Configuration;
使用System.Web;
使用System.Web.Security;
使用System.Web.UI;
使用System.Web.UI.WebControls;
使用System.Web.UI.WebControls.WebParts;
使用System.Web.UI.HtmlControls;
使用System.IO;
使用iTextSharp.text;
使用iTextSharp.text.pdf;
使用iTextSharp.text.html;
使用iTextSharp.text.html.simpleparser;

公共局部类_Default:System.Web.UI.Page
{
受保护的void Page_Load(对象发送者,EventArgs e)
{
DataTable dt = new DataTable();
字符串strConnString = System.Configuration.ConfigurationManager.ConnectionStrings ["conString"].ConnectionString;
字符串strQuery =从ID按顺序从tblFiles中选择*";
SqlCommand cmd =新的SqlCommand(strQuery);
SqlConnection con =新的SqlConnection(strConnString);
SqlDataAdapter sda =新的SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
试试
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch(ex ex例外)
{
Response.Write(ex.Message);
}
终于
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
受保护的void Export_Grid(对象发送者,EventArgs e)
{
按钮btn =(按钮)发送器;
开关(btn.CommandArgument)
{
大小写字":
Word_Export();
休息;
案例"Excel":
Excel_Export();
休息;
案例"PDF":
PDF_Export();
休息;
}
}
公共重写void VerifyRenderingInServerForm(Control control)
{
/*验证控件是否已呈现*/
}
私有void Excel_Export()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
附件; filename = GridViewExport.xls");
Response.Charset =";
Response.ContentType ="application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw =新的HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
for(int i = 0; i< GridView1.Rows.Count; i ++)
{
GridViewRow行= GridView1.Rows [i];
//将文本样式应用于每个行
row.Attributes.Add("class","textmode");
}
GridView1.RenderControl(hw);

//将数字格式化为字符串的样式
字符串样式= @".textmode {mso-number-format:\ @;}";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}

 受保护的 字符串 GetUrl(字符串 imagepath)
   {
       字符串 []拆分= Request.Url.AbsoluteUri.Split(' 如果(长度>  =  2 )
       {
           字符串 url = splits [ 0 ] + " //";
            for ( int  i =  2 ; i < 拆分.长度- 1 ; i ++)
           {
               url + = splits [i];
               url + = " ;
           }
           返回 url + imagepath;
       }
       返回图像路径;
   } 


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]

解决方案

convert your image data in bmp format.


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.


/*----------------------------------------------*/
//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();
}

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;
   }


这篇关于如何从Gridview将图像导出到Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆