GridView的操作<2>:导出Excel[方案二]

GridView导出Excel文件,方案二:直接向响应写入Table

偶然的机会,由于没有写Content-Type,响应输出了一个Table,

由此而知响应中写入的方案一中的GridView的DefaultView其实只有一个没有任何样式属性的Table

那么向响应中输入一个Table自然也可以达到相同的目的

而且,还可以方便的设置Excel一个Sheet的不同的列名

private void OutToExcel()
{
HttpContext curContext 
= System.Web.HttpContext.Current;
StringWriter strWriter 
= new StringWriter();
curContext.Response.ContentType 
= "application/vnd.ms-excel";

curContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + 

HttpUtility.UrlEncode("属性-属性值对应表.xls"));


curContext.Response.ContentEncoding 
= Encoding.UTF8;

curContext.Response.Charset = "UTF8";


//CDT获取和页面上的GridView的数据源获取方式相同
DataTable CDT 
= DatasInfo.DataLayer.DBOper.w_CategoryProperty.GetViews();
string txt = "<table width='700' border='1' cellpadding='0' cellspacing='0'>"+
"<caption>属性-属性值对应</caption>";
txt 
+= "<tr>";
txt 
+= "<td>名称</td>";
txt 
+= "<td>属性ID</td>";
txt 
+= "<td>值ID</td>";
txt 
+= "</tr>";
foreach (DataRow dr in CDT.Rows)
{
   txt 
+= "<tr>";
   txt 
+= "<td>" + dr["CName"].ToString() + "</td>";
   txt 
+= "<td>" + dr["CID"].ToString() + "</td>";
   txt 
+= "<td>" + dr["PID"].ToString() + "</td>";
   txt 
+= "</tr>";
}
txt 
+= "</table>";

curContext.Response.Write(txt);
curContext.Response.End();
}
原文地址:https://www.cnblogs.com/lixx/p/1289662.html