62,046
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// GridView导出到Excel
/// </summary>
/// <param name="exportTargetGridView">目标GridView</param>
/// <param name="filename">文件名称</param>
public static void ExportExcel(GridView exportTargetGridView, string filename)
{
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlPathEncode(filename + ".xls"));
HttpContext.Current.Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
PrepareGridViewForExport(exportTargetGridView);//调用模式化特殊元素
exportTargetGridView.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
/// <summary>
/// 使用GridView导出excel表格,对特殊的控件进行模式化处理
/// </summary>
/// <param name="gv">模式化特殊元素的函数 </param>
public static void PrepareGridViewForExport(Control gv)
{
HyperLink lb = new HyperLink();
LinkButton bt = new LinkButton();
Literal l = new Literal();
string name = String.Empty;
RadioButton rb = new RadioButton();
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(HyperLink))
{
l.Text = (gv.Controls[i] as HyperLink).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(LinkButton))//替换
{
l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
DropDownList dl = gv.Controls[i] as DropDownList;
for (int j = 0; j < dl.Items.Count; j++)
{
rb.Text = dl.Items[j].Text;
if (rb.Text == dl.SelectedItem.Text)
rb.Checked = true;
gv.Controls.AddAt(i, rb);
}
gv.Controls.Remove(dl); //移除DropDownlist
}
else if (gv.Controls[i].GetType() == typeof(CheckBox))
{
l.Text = (gv.Controls[i] as CheckBox).Checked ? "" : "";
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(ImageButton))
{
l.Text = "图片";
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
PrepareGridViewForExport(gv.Controls[i]);
}
}
}