在Response.End()之后执行代码

时间:2015-03-03 01:33:43

标签: c# export-to-excel

我无法在Response.End()之后执行代码。

我使用它将数据表/ ASP表导出到MS Excel(.xls)。

导出完成但我的Gridview不再加载。我用来加载gridview的命令是在Response.End()。

之后写的

我尝试使用HttpContext.Current.ApplicationInstance.CompleteRequest();,但没有帮助。

我也试过Response.Redirect("Charges_Trs.aspx", false);仍然无法正常工作..

请帮助..这是我的代码

lblNotif.Text = "Selected items have been posted. Exporting XLS ... (will be saved in your desktop)";
exportToExcel(dt); //calls the function to export the datatable to excel, i passed dt=datatable to this function
timerNotif.Enabled = true;
btnSearch_Click(null, null); //called the event of a button that loads the gridview

这是函数exporttoexcel()

public void exportToExcel(DataTable dt)
    {

        Table dTable = new Table();
        TableRow dTableRow = new TableRow();

        //Column Headings
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            TableCell tCell = new TableCell();
            tCell.Text = dt.Columns[i].ToString();
            dTableRow.Cells.Add(tCell);
        }

        dTable.Rows.Add(dTableRow);

        //Rows
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dTableRow = new TableRow();
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                TableCell tCell = new TableCell();
                dTableRow.Cells.Add(tCell);
            }
            dTable.Rows.Add(dTableRow);
        }

        if (Response.IsClientConnected)
        {
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=PostedCharges" + DateTime.Now.ToString("MMddyyyy") + ".xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            dTable.RenderControl(hw);
            string style = @"<style> .textmode { mso-number-format:\@; } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
    }

1 个答案:

答案 0 :(得分:0)

你可以尝试在调用export之后在btnSearch click事件中添加代码(希望它是用一些数据绑定网格),而不是调用click事件。