GridView的操作:匯出Excel[方案二]

來源:互聯網
上載者:User

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

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.