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