调用 ExportGridViewToExcel(dt, HttpContext.Current.Response);
private void ExportGridViewToExcel(DataTable tb, HttpResponse response)
{
response.Clear();
response.Charset = "";
response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
response.ContentEncoding = System.Text.Encoding.UTF8;//System.Text.Encoding.GetEncoding("GB2312");
response.ContentType = "application/ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
GridView newDataGrid = new GridView();
newDataGrid.EnableViewState = false;
newDataGrid.AllowSorting = false;
newDataGrid.GridLines = GridLines.Vertical;
newDataGrid.HeaderStyle.Font.Bold = true;
newDataGrid.DataSource = tb.DefaultView;
newDataGrid.DataBind();
newDataGrid.RenderControl(htmlTextWriter);
response.Write(stringWriter.ToString());
}