if (GridView1.Rows.Count == 0)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('无数据导出!');</script>");
        }
        else
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new System.IO.StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            Page page = new Page();
            HtmlForm form = new HtmlForm();
            GridView1.EnableViewState = false;
            page.EnableEventValidation = false;
            page.DesignerInitialize();
            page.Controls.Add(form);
            form.Controls.Add(GridView1);
            page.RenderControl(htw);
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/vnd.ms-excel";
            string name = "Domain-alone-" + System.DateTime.Now.ToShortDateString();
            Response.AddHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
            Response.Charset = "gb2312";
            Response.ContentEncoding = Encoding.Default;
            Response.Write(sb.ToString());
            Response.End();
        }

本文转载:CSDN博客