我們做一個測試程式:
1、在空白頁上建立一個GridView,給它指定一個資料來源,填充一些測試資料(此例中是GridView1)。
2、給頁面添加一個按鈕(此例中是btnExport),在按鈕的單擊事件中填入如下代碼:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
Response.AppendHeader("content-disposition", "attachment;filename=\"" + HttpUtility.UrlEncode("[" + DateTime.Now.ToString("yyyy-MM-dd") + "]", System.Text.Encoding.UTF8) + ".xls\"");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
// If you want the option to open the Excel file without saving then
// comment out the line below
//Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
3、重載方法VerifyRenderingInServerForm,否則VS編譯器報錯。
public override void VerifyRenderingInServerForm(Control control)
{
}
4、運行頁面,單擊按鈕,彈出提示框,要你選擇儲存或開啟一個以目前時間命名的Excel檔案。
注意事項:若表格中有中文必須將編碼格式設定為gb2312,如下:
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
必須重載VerifyRenderingInServerForm方法。
還可以匯出成各種形式的文檔,只需把Response.ContentType的值設定成別的就可以,具體值可以從網上查到,如要匯出成Word格式可以將Response.ContentType的值設定成"application/word.doc"。