将gridview导出到Excel后,页面加载没有结束

时间:2014-01-21 17:59:53

标签: c# javascript asp.net excel pageload

我正在尝试将gridview数据导出到excel。一切都可以用于导出但是在页面加载没有结束之后。

这是母版页中“请稍候”的脚本(它显示了一个gif并说“请等待页面加载时”):

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    function ShowProgress() {
        setTimeout(function () {
            var modal = $('<div />');
            modal.addClass("modal");
            $('body').append(modal);
            var loading = $(".loading");
            loading.show();
            var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
            var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
            loading.css({ top: top, left: left });
        }, 200);
    }
    $('form').live("submit", function () {
        ShowProgress();
    });
</script>

这是我导出的类:

public static void Export(string fileName, GridView gv)
{
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader(
        "content-disposition", string.Format("attachment; filename={0}", fileName));
    HttpContext.Current.Response.ContentType = "application/ms-excel";

    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter htw = new HtmlTextWriter(sw))
        {
            //  Create a form  to contain the grid
            Table table = new Table();

            //  add  the header row to the table
            if (gv.HeaderRow != null)
            {

                GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                table.Rows.Add(gv.HeaderRow);
                //color the header
                table.Rows[0].BackColor = gv.HeaderStyle.BackColor;
                table.Rows[0].ForeColor = gv.HeaderStyle.ForeColor;
            }

            //  add each of the data  rows to the table
            foreach (GridViewRow row in gv.Rows)
            {
                GridViewExportUtil.PrepareControlForExport(row);
                table.Rows.Add(row);
            }

            //  add the footer row to the table
            if (gv.FooterRow != null)
            {
                GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                table.Rows.Add(gv.FooterRow);
            }


            table.GridLines = gv.GridLines;
            //  render the table into the htmlwriter

            table.RenderControl(htw);
            //  render the htmlwriter into the response
            HttpContext.Current.Response.Write(sw.ToString());
            HttpContext.Current.Response.End();

        }
    }

这就是我在母版页中调用方法的地方:

    GridView gridview = (GridView)ContentPlaceHolder1.FindControl("gridview_sales");
    gridview.AllowPaging = false;
    gridview.DataBind();
    GridViewExportUtil.Export("SalesList.xls", gridview);

1 个答案:

答案 0 :(得分:0)

这是因为只有来自服务器端的响应。在您的情况下,该响应采用excel文件的形式。通过在JavaScript中设置超时以及删除“请稍候”gif的代码来解决此问题的一种方法。