我有Gridview
并且我有三个选项可以将数据导出到 Excel 表:
- 当前页面
- 所有页面
- 前100行
它适用于当前,但其他选项不起作用。
代码:
protected void btnExportGrid_Click(object sender, EventArgs e)
{
Table table = new Table
{
GridLines = this.gv_RquestedOrdres.GridLines
};
if (this.rdoBtnListExportOptions.SelectedIndex == 1)
{
this.gv_RquestedOrdres.AllowPaging = false;
this.gv_RquestedOrdres.DataBind();
}
else if (this.rdoBtnListExportOptions.SelectedIndex == 2)
{
this.gv_RquestedOrdres.PageSize = 100;
this.gv_RquestedOrdres.DataBind();
}
GridViewExportUtil.Export("Orders.xls", this.gv_RquestedOrdres);
}
private string Gridview(Panel gv)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
gv.RenderControl(hw);
return sb.ToString();
}
GridViewExportUtil 类:
public class GridViewExportUtil
{
public static void Export(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
using (StringWriter writer = new StringWriter())
{
using (HtmlTextWriter writer2 = new HtmlTextWriter(writer))
{
Table table = new Table();
if (gv.HeaderRow != null)
{
PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
foreach (GridViewRow row in gv.Rows)
{
PrepareControlForExport(row);
table.Rows.Add(row);
}
if (gv.FooterRow != null)
{
PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
table.RenderControl(writer2);
HttpContext.Current.Response.Write(writer.ToString());
HttpContext.Current.Response.End();
}
}
}
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control control2 = control.Controls[i];
if (control2 is LinkButton)
{
control.Controls.Remove(control2);
control.Controls.AddAt(i, new LiteralControl((control2 as LinkButton).Text));
}
else if (control2 is ImageButton)
{
control.Controls.Remove(control2);
control.Controls.AddAt(i, new LiteralControl((control2 as ImageButton).AlternateText));
}
else if (control2 is HyperLink)
{
control.Controls.Remove(control2);
control.Controls.AddAt(i, new LiteralControl((control2 as HyperLink).Text));
}
else if (control2 is DropDownList)
{
control.Controls.Remove(control2);
control.Controls.AddAt(i, new LiteralControl((control2 as DropDownList).SelectedItem.Text));
}
else if (control2 is CheckBox)
{
control.Controls.Remove(control2);
control.Controls.AddAt(i, new LiteralControl((control2 as CheckBox).Checked ? "True" : "False"));
}
if (control2.HasControls())
{
PrepareControlForExport(control2);
}
}
}
}