/// <summary>
/// 直接由GridView导出Excel
/// </summary>
/// <param name="ctl">控件(一般是GridView)</param>
/// <param name="FileName">导出的文件名</param>
/// <param name="removeIndexs">要移除的列的索引数组(因为有时我们并不希望把GridView中的所有列全部导出)</param>
/// <param name="pages"></param>
public void ControlToExcel(System.Web.UI.WebControls.GridView ctl, string FileName, string[] removeIndexs, System.Web.UI.Page pages)
{
if (removeIndexs != null)
{
foreach (string index in removeIndexs)
{
ctl.Columns[int.Parse(index)].Visible = false;
}
}
pages.Response.Charset = "UTF-8";
pages.Response.ContentEncoding = System.Text.Encoding.UTF7;
pages.Response.ContentType = "application/ms-excel";
FileName = System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);
pages.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
ctl.RenderControl(hw);
pages.Response.Write(tw.ToString());
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
GridView导出Excel
最新推荐文章于 2024-09-17 13:50:09 发布