导出到Excel文件时,GridView导出不返回任何数据

本文关键字:返回 任何 数据 GridView Excel 文件 | 更新日期: 2023-09-27 18:22:51

由于某种原因,我在将GridView导出到Excel时遇到问题。我有两个按钮,一个是搜索,一旦用户提供了所需的信息,它就会处理搜索。另一个按钮是Export,它基本上处理将gridview导出到excel的操作。

我的问题是,当用户点击搜索按钮,然后他们想将数据导出到excel时,他们需要点击导出按钮。一切都很好,直到现在,当excel文件被查看时,没有数据被导出。这是我的两个按钮的代码:

任何帮助都将不胜感激,谢谢。

protected void search(object sender, EventArgs e)
{
    odbc.Open();
    ds = new DataSet();
    cmd = new OdbcCommand("SELECT XHLBCD AS LOCATION, XHLCST AS STATUS, XHEXUN AS EXCESS, XHSHUN AS SHORT, XHCNTD AS DATE_COUNTED FROM " +
                            "WM242BASD.XHCTRL00 WHERE XHCNTD BETWEEN '" + fromdate.Text + "' AND '" + todate.Text + "'", odbc);
    cmd.CommandType = CommandType.Text;
    cmd.Connection = odbc;
    oda = new OdbcDataAdapter(cmd);
    oda.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
    odbc.Close();
}
protected void export_OnClick(object sender, EventArgs e)
{
    // Let's hide all unwanted stuffing
    GridView1.AllowPaging = false;
    GridView1.AllowSorting = false;
    // Let's bind data to GridView
    BindGrid();
    //Change the color back to white
    GridView1.HeaderRow.Style.Add("background-color", "#ffffff");
    //Apply color to the header
    GridView1.HeaderRow.Cells[0].Style.Add("background-color", "#e0e0e0");
    GridView1.HeaderRow.Cells[1].Style.Add("background-color", "#e0e0e0");
    GridView1.HeaderRow.Cells[2].Style.Add("background-color", "#e0e0e0");
    GridView1.HeaderRow.Cells[3].Style.Add("background-color", "#e0e0e0");
    GridView1.HeaderRow.Cells[4].Style.Add("background-color", "#e0e0e0");
    // Let's output the GridView
    Response.Clear();
    Response.ContentType = "application/vnd.xls";
    Response.AddHeader("content-disposition", "attachment;filename=" + reportid + ".xls");
    StringWriter swriter = new StringWriter();
    HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
    GridView1.RenderControl(hwriter);

    Response.Write(swriter.ToString());
    Response.End();
}
private void BindGrid()
{
    GridView1.DataBind();
}

导出到Excel文件时,GridView导出不返回任何数据

在这两种情况下,您都需要为网格提供一个数据源,因为此时网格视图还没有数据源,所以您无法从导出中获得任何数据。

将代码从搜索方法移动到数据库方法中,并从两个事件处理程序调用该方法。

此外,您编写的SQL参数对SQL注入攻击是完全开放的。