ASP.NETGridView导出excle

public void ExportToExcel(Page myPage, GridView ctl, string filename)
{
//ctl.BottomPagerRow.Visible = false;//导出到Excel表后,隐藏分页部分

ctl.Columns[0].Visible = false;//隐藏“编辑”列

//ctl.AllowPaging = false;//取消分页,便于导出所有数据,不然只能导出当前页面的几条数据

//DataView dv = getDt().DefaultView;
//ctl.DataSource = dv;
//ctl.DataBind();
/*
foreach (GridViewRow dg in this.gdvSort.Rows)
{
dg.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
dg.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
dg.Cells[6].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
dg.Cells[8].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
}
*/
HttpResponse Response;
Response = myPage.Response;
foreach (TableCell tc in ctl.HeaderRow.Cells)
{
// TableCell里的每个Control
foreach (Control c in tc.Controls)
{
// 如果控件继承自接口IButtonControl
if (c.GetType().GetInterface("IButtonControl") != null && c.GetType().GetInterface("IButtonControl").Equals(typeof(IButtonControl)))
{
// 如果该控件不是“导出Excel”按钮则把button转换成文本
tc.Controls.Clear();
tc.Text = ((IButtonControl)c).Text;
}
}
}

bool CurrCtlVisible = ctl.Visible;
ctl.Visible = true;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.ContentType = "application/ms-excel";
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
ctl.Page.EnableViewState = true;
ctl.Visible = CurrCtlVisible;
}

//////////////////

// 隐藏指定的列
if (hideColumns != null)
{
foreach (int columnIndex in hideColumns)
{
if (columnIndex < gridView.Columns.Count)
{
gridView.Columns[columnIndex].Visible = false;
}
}
}

// 如果HeaderRow里的控件是button的话,则把它替换成文本
foreach (TableCell tc in gridView.HeaderRow.Cells)
{
// TableCell里的每个Control
foreach (Control c in tc.Controls)
{
// 如果控件继承自接口IButtonControl
if (c.GetType().GetInterface("IButtonControl") != null && c.GetType().GetInterface("IButtonControl").Equals(typeof(IButtonControl)))
{
// 如果该控件不是“导出Excel”按钮则把button转换成文本
tc.Controls.Clear();
tc.Text = ((IButtonControl)c).Text;
}
}
}

原文地址:https://www.cnblogs.com/zyh-C/p/9949289.html