简体   繁体   中英

asp.net datagrid export to excel c# issue

I have classic asp.net website. I have a datagrid that i would like to export as excel sheet. The site uses windows authentication.

I picked up the code while googling for a solution. Here is what i am experiencing in FF and Chrome and need help to rectify it:

  1. some times the file download will happen without any issue, but if i keep the window inactive for a minute or so and then try again, eiter i get page not found issue or the browser will keep on asking for login (kind of stuck in a loop).

  2. some times when the export button gets clicked, FF just keeps on displaying windows login popup, like it is stuck in a loop.

Button:

<asp:Button ID="cmdExportDataGridToExcel_Click" runat="server" OnClick="cmdExportToExcel_Click" CssClass="StandardText" Text="Export to Excel" Width="120px" Height="33px"></asp:Button>

Code:

protected void cmdExportDataGridToExcel_Click(object sender, System.EventArgs e)
    {
        //export to excel
        Response.Clear();
        var userName = CommonMethods.GetUserId();
        var fileName = string.Format("ScheduledOrdersReport-{0}-{1:yyyyMMddhhmmsstt}.xls", userName, DateTime.Now);
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
        Response.ContentType = "application/vnd.ms-excel";
        Response.Charset = "";
        hsGrid.AllowPaging = false;
        this.BindHSGrid(false, string.Empty);
        //this.EnableViewState = false;
        var oStringWriter = new StringWriter();
        var oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
        this.ClearControls(hsGrid);
        hsGrid.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString());
        Response.End();
    }

private void ClearControls(Control control)
    {
        for (int i = control.Controls.Count - 1; i >= 0; i--)
        {
            ClearControls(control.Controls[i]);
        }
        if (!(control is TableCell))
        {
            if (control.GetType().GetProperty("SelectedItem") != null)
            {
                LiteralControl literal = new LiteralControl();
                control.Parent.Controls.Add(literal);
                try
                {
                    literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control, null);
                }
                catch
                {
                }
                control.Parent.Controls.Remove(control);
            }
            else if (control.GetType().GetProperty("Text") != null)
            {
                LiteralControl literal = new LiteralControl();
                control.Parent.Controls.Add(literal);
                literal.Text = (string) control.GetType().GetProperty("Text").GetValue(control, null);
                control.Parent.Controls.Remove(control);
            }
        }
    }

Update 1 I have tested it by putting the data in a session and then creating an excel from the session. It also is resulting in the same error.

var dv = (DataView) Session["ScheduledOrdersReport"];

            Response.Clear();
            var userName = CommonMethods.GetUserId();
            var fileName = string.Format("ScheduledOrdersReport-{0}-{1:yyyyMMddhhmmsstt}.xls", userName, DateTime.Now);

            Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel"; //"application/vnd.xls";

            var stringWrite = new StringWriter();
            var htmlWrite = new HtmlTextWriter(stringWrite);

            var g = new GridView();
            g.DataSource = dv;
            g.DataBind();

            g.RenderControl(htmlWrite);
            Response.Write(stringWrite.ToString());
            Response.End();

Update 2 I just did another test by opening a popup and then using update 1 code on it. No issues, on click or keeping the page for some time and then clicking the button again.

Looks like it is the post back and response clear and end issue.

I just simply can't find anything at this time to fix this properly. May be i need a little break.

What about to start a webclient? and set the NetworkCredentials? Then you must'nt login every time...

like:

`using(Webclient webclient = new Webclient())
   {
     webClient http = new Webclient();
     http.Credentials = new NetworkCredential("YourUsername", "YourPassword");
    }

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM