导出当前gridview数据

时间:2014-05-15 12:08:14

标签: c# asp.net .net gridview export-to-excel

我正在使用此代码导出gridview数据。我的页面中有一个下拉列表,当我选择下拉值时,gridview中的数据会发生变化,我只需要将当前数据导出到excel中。

protected void ExporttoExcel(object sender, EventArgs e)
{
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment; filename=Report.xls");
    Response.ContentType = "application/vnd.xls";
    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    GridView1.RenderControl(htmlWrite);
    Response.Write(stringWrite.ToString());
    Response.End();   
}

我正在使用分页,当我最初导出而没有选择下拉值时,我需要导出所有数据,但现在只导出第一页中的数据。

任何人都能纠正我错在哪里吗?

3 个答案:

答案 0 :(得分:0)

我有一个自定义方法,用于从Datatable-Gridvieww导出格式化样式的Excel。您可以使用它,通过为表格变量分配绑定Gridview的数据表(在分页之前的整个数据表)

private void ExportToExcel(DataTable table, GridView gv)
    {

        Response.ClearContent();
        Response.Charset = your charset//"Windows-1253";
        Response.ContentEncoding = your encoding//Encoding.UTF8;
        string attachment = "attachment; filename=test.xls";
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");

        HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
        HttpContext.Current.Response.Write("<BR><BR><BR>");
        HttpContext.Current.Response.Write("<Table border='1' bgColor='#ffffff' " +
          "borderColor='#000000' cellSpacing='0' cellPadding='0' " +
          "style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>");
        int columnscount = table.Columns.Count;

        for (int j = 0; j < columnscount; j++)
        {
            HttpContext.Current.Response.Write("<Td style='background-color: #C0C0C0;' align=" + "center" + ">");
            HttpContext.Current.Response.Write("<B>");
            HttpContext.Current.Response.Write(table.Columns[j].ToString());
            HttpContext.Current.Response.Write("</B>");
            HttpContext.Current.Response.Write("</Td>");
        }
        HttpContext.Current.Response.Write("</TR>");
        foreach (DataRow row in table.Rows)
        {
            HttpContext.Current.Response.Write("<TR>");
            for (int i = 0; i < table.Columns.Count; i++)
            {
                HttpContext.Current.Response.Write("<Td align=" + "center" + ">"); ;
                HttpContext.Current.Response.Write(row[i].ToString());
                HttpContext.Current.Response.Write("</Td>");
            }

            HttpContext.Current.Response.Write("</TR>");
        }
        HttpContext.Current.Response.Write("</Table>");
        HttpContext.Current.Response.Write("</font>");
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
    }

答案 1 :(得分:0)

您可以将SQL查询结果保存在DataTable中,并将该DataTable保存在ViewState或会话中。然后单击导出按钮时,从ViewState中检索DataTable 并创建一个将DataTable作为其源的虚拟GridView。

这样的事情:

   protected void ExporttoExcel(object sender, EventArgs e)
   {
       //First, retrieve the DataTable from ViewState
       DataTable Dt = new DataTable();
       Dt = (DataTable)ViewState["DtData"];

       //Now you have the data, create a dummy GridView that will be used for exporting
       GridView grdView = new GridView();
       grdView.AllowPaging = false;
       grdView.DataSource = Dt;
       grdView.DataBind();

       //Do the Exporting stuff
       Response.Clear();
       Response.AddHeader("content-disposition", "attachment; filename=Report.xls");
       Response.ContentType = "application/vnd.xls";
       System.IO.StringWriter stringWrite = new System.IO.StringWriter();
       System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
       grdView.RenderControl(htmlWrite);
       Response.Write(stringWrite.ToString());
       Response.End();
   }

这样,每次更改下拉列表值时,将选定的SQL查询结果保存在数据表中,然后保存在ViewState中并导出。

当然,如果您可以使用下拉列表代码更新您的问题,或者您如何设置GridView数据源,我会更新此答案。

希望这有帮助。

答案 2 :(得分:-1)

禁用GridView分页然后渲染。您可能还需要进行绑定。

protected void ExporttoExcel(object sender, EventArgs e)
{
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment; filename=Report.xls");
    Response.ContentType = "application/vnd.xls";
    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

    // ************************
    GridView1.AllowPaging = false; // <- disable paging then render
    // also do the binding
    GridView1.DataSource = myDataSource;
    GridView1.DataBind();
    // ************************

    GridView1.RenderControl(htmlWrite);
    Response.Write(stringWrite.ToString());
    Response.End();
}

编辑(工作示例)

ASPX(GridView和导出Button):

<asp:GridView ID="grd1" runat="server" AllowPaging="true" PageSize="10" AutoGenerateColumns="false" OnPageIndexChanging="grd1_PageIndexChanging">
    <Columns>
        <asp:BoundField DataField="StudentID" HeaderText="Student ID" />
        <asp:BoundField DataField="StudentName" HeaderText="Student Name" />
        <asp:BoundField DataField="FatherName" HeaderText="Father Name" />
    </Columns>
</asp:GridView>
<asp:Button ID="btnExport" runat="server" Text="Export" OnClick="btnExport_Click" />

代码背后:

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGridView();
    }
}

private void BindGridView()
{
    using (var dtStudent = this.GetStudentData())
    {
        this.grd1.DataSource = dtStudent;
        this.grd1.DataBind();
    }
}

private DataTable GetStudentData()
{
    var dtStudent = new DataTable();
    dtStudent.Columns.Add("StudentID");
    dtStudent.Columns.Add("StudentName");
    dtStudent.Columns.Add("FatherName");

    for (int i = 0; i < 20; i++)
    {
        var sIndex = i.ToString("00");
        dtStudent.Rows.Add("Student-" + sIndex, "Name-" + sIndex, "Father-" + sIndex);
    }

    return dtStudent;
}

protected void grd1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    this.grd1.PageIndex = e.NewPageIndex;
    this.BindGridView();
}

protected void ExporttoExcel()
{
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment; filename=Report.xls");
    Response.ContentType = "application/vnd.xls";
    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

    // ************************
    this.grd1.AllowPaging = false; // <- disable paging then render
    this.BindGridView();
    // ************************

    this.grd1.RenderControl(htmlWrite);
    Response.Write(stringWrite.ToString());
    Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
{
    //base.VerifyRenderingInServerForm(control);
}

protected override void Render(HtmlTextWriter writer)
{
    if (this._Export)
        this.ExporttoExcel();
    else
        base.Render(writer);
}

private bool _Export = false;

protected void btnExport_Click(object sender, EventArgs e)
{
    this._Export = true;
}