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

posted on 2016-09-19 15:16  buy0769  阅读(285)  评论(0编辑  收藏  举报