2012-02-07 86 views
1

我出于某种原因导致将GridView导出到Excel时出现问题。我有两个按钮,一个是搜索,一旦用户提供了所需的信息,就会处理搜索。另一个按钮是基本上处理gridview出口excel的导出。导出到Excel文件时,GridView导出不会返回任何数据

我的问题是,当用户点击搜索按钮,然后他们想要将数据导出为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(); 
} 

回答

2

你需要给电网一个数据源在这两种情况下,你从你的出口没有得到数据,因为在GridView还没有得到在该点的数据源。

将代码从搜索方法移到您的databaind方法中,并从两个事件处理函数中调用方法。

另外使用SQL参数你的代码是全开的SQL注入攻击。

+0

谢谢。这工作,是的,我使用这种方式进行测试,只有一次我进入生产我使用SQL参数和StoreProcedures – jorame 2012-02-07 19:50:47