关闭

DataGrid控件的常见数据导出EXCEL技术(1)

637人阅读 评论(0) 收藏 举报
 
绑定到DataGrid控件中的数据导出Excel表有几种比较常见的方式.现一一介绍.
方式一:直接导出,不需要任何加工.这种对那些内容只有一页,而且是纯数据不含按钮的尤其合适.
if (dgrid.Visible==false)
{
     Label5.Visible=true;   Label5.Text="您还没有确认导出的内容,请先查找";
}
else
{
     Label5.Visible=false;
     Response.Clear(); Response.Buffer=trueResponse.Charset = "gb2312";//导出中文字体
Response.AppendHeader("Content-Disposition","attachment;filename=YieldCompareForms.xls");
     Response.ContentEncoding=System.Text.Encoding.GetEncoding("gb2312");
     Response.ContentType="application/ms-excel";
     this.EnableViewState=false;
     //定义一个输出流
     System.IO.StringWriter Ostring=new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter ohtmlTextWrite=new System.Web.UI.HtmlTextWriter(Ostring);
//目标数据绑定到输入输出流
this.dgrid.RenderControl(ohtmlTextWrite);
Response.Write(Ostring.ToString());       Response.End();
}
方式二:对DataGrid内容含有多页,但依然是纯数据的可采用此法.
Response.Clear ();Response.Buffer = true; Response.Charset = "gb2312";
string tablename =Session["unique_id"].ToString();//表名以productid为名字
string str="attachment;filename="+tablename+".xls";
Response.AppendHeader("Content-Disposition",str);//与下面这句等价
//Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls");
Response.ContentEncoding=System.Text.Encoding.GetEncoding("gb2312");
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter=new System.Web.UI.HtmlTextWriter(oStringWriter);
GC.Collect ();
string strsql ="select uniqueid,testitem,testindex,result,speccount,errorcode from "+Session["projectname"].ToString()+".testiteminfo where uniqueid='"+tablename.ToString()+"' order by testindex";
string project=Session["projectname"].ToString();
OracleConnection conn=new OracleConnection(StoneFunction.neworacleconn(project));
conn.Open();
 OracleDataAdapter OracleDa=new OracleDataAdapter(strsql,conn);
DataSet ds=new DataSet();
OracleDa.Fill(ds);
DataTable dt=ds.Tables[0];
StringWriter sw=new StringWriter();
//Excel表格第一行
sw.WriteLine("Uniqueid/tTestitem/tTestindex/tResult/tSpeccount/tErrorcode");
foreach(DataRow dr in dt.Rows)
{
sw.WriteLine(dr["Uniqueid"]+"/t"+dr["testitem"]+"/t"+dr["testindex"]+"/t"+dr["result"]+"/t"+dr["speccount"]+"/t"+dr["errorcode"]);
}
sw.Close(); Response.Write(sw); Response.End();
 
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:131487次
    • 积分:596
    • 等级:
    • 排名:千里之外
    • 原创:52篇
    • 转载:4篇
    • 译文:1篇
    • 评论:48条
    最新评论