前台:
<div>
<asp:GridView ID="GridView1" runat="server" >
</asp:GridView>
<br />
<asp:Button ID="btnExportToExcel" runat="server"
onclick="btnExportToExcel_Click" Text="导出数据到Excel" />
</div>
后台:
/// <summary>
/// 将GridView的数据输出到Excel文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
if (GridView1.Rows.Count == 0)
{
return;
}
Response.ClearContent();
Response.ContentEncoding = Encoding.Default;
Response.AddHeader("content-disposition", "attatchment;filename=" + HttpUtility.UrlEncode("我的Excel.xls", Encoding.UTF8));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
//必须重载此方法,以便支持上面的导出操作
public override void VerifyRenderingInServerForm(Control control)
{
}