日期:2014-05-18  浏览次数:20455 次

GridView如何将分页数据全部导出为EXCEL?(附我的代码)
我已实现将GridView导出至Excel,但由于我的Gridview是分页的,所以导出Excel时只能导出当前页的数据,我已在后台设置了

GridView1.AllowPaging = false;

但这句话好像没起作用。现贴上代码,请各高手指教!


前台有一个GridView控件,和Button控件。
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
  AutoGenerateColumns="False" DataKeyNames="serialID" DataSourceID="SqlDataSource2">
</asp:GridView>

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="导出至Excel" />

后台代码为:

 protected void Button1_Click(object sender, EventArgs e)
  {
  string style = @"<style> .text { mso-number-format:\@; } </script> ";

  Response.ClearContent();

  Response.AddHeader("content-disposition", "attachment; filename=ShipExcelFile.xls");

  Response.ContentType = "application/ms-excel";

  Response.Charset = "GB2312";

  Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
   
  StringWriter sw = new StringWriter();

  HtmlTextWriter htw = new HtmlTextWriter(sw);

  GridView1.AllowPaging = false; //就是这句话,怎么不起作用那?
   
  GridView1.RenderControl(htw);
   
  Response.Write(style);
   
  Response.Write(sw.ToString());

  Response.End();

  }

  public override void VerifyRenderingInServerForm(Control control)
  {

  }
  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
  e.Row.Cells[1].Attributes.Add("class", "text");
  }
  }

------解决方案--------------------
//导出的方法
private void Export(string FileType, string FileName)
{
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
// turn off paging 
gv_KeywordManage.AllowPaging = false;
BindGrid(); 

gv_KeywordManage.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();

// turn the paging on again 
gv_KeywordManage.AllowPaging = true;
BindGrid();

}

关键是AllowPaging的false和true. 找我的结构写就可以了.

------解决方案--------------------
protected void Button2_Click(object sender, EventArgs e)
//按button2将gridview将数据导出。
{
GridView1.AllowPaging = false; //清除分页
GridView1.AllowSorting = false; //清除排序
pbind(); //你绑定gridview1数据源的那个函数。
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=dpdgxkh.xls"); //.xls的文件名可修改
Response.ContentEncoding = System.Text.Encoding.UTF7