Click here to Skip to main content
15,885,824 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
i wants to use the BackgroundWorker in asp.net with ajax to get the data from the data base and export it into excel. when click the start button backgound worker will start load the data from database and write into excel when process complete that excel will download. these process show to use through Progress bar.

but problem in httpcontext(it may wrong), when click the start button excel file are created but it's not download. please fix the problem.
i given the code

C#
 protected void Page_Load(object sender, EventArgs e)   
    {
        _backgroundWorker.WorkerReportsProgress=true;
        _backgroundWorker.WorkerSupportsCancellation = true;
        _backgroundWorker.DoWork += new DoWorkEventHandler(_backgroundWorker_DoWork);
        _backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(_backgroundWorker_ProgressChanged);
        _backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_backgroundWorker_RunWorkerCompleted);
      
      
    }

protected void btnStart_Click(object sender, EventArgs e)
    {

        // Start(ProgressBar1.Progress, HttpContext.Current);
        if (!_backgroundWorker.IsBusy)
        {
            _backgroundWorker.RunWorkerAsync();
        }

    }

    void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        string display = "Message Pop-up!";
        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true);
    }

    void _backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {

        ProgressBar1.SetProgress(e.ProgressPercentage);


    }

    void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {

        Start(ProgressBar1.Progress, _httpContext);
    }







    private void Start(Progress progress, HttpContext context)
     {
        ProductBussiness productBussiness = new ProductBussiness();
        DataTable dataTable = new DataTable();
        StringBuilder builder = new StringBuilder();
        Table htmltable=new Table();

        int Totalcount = productBussiness.GetCount();
        int page = Totalcount / 100;
        double progresPercent = 100.00 / page;
        for (int i = 1; i <=page; i++)
        {
             dataTable = productBussiness.GetProductData(i);
             int percent=(int)(i * progresPercent);
            _backgroundWorker.ReportProgress(percent, progress);



            progress.SetProgress((i * progresPercent)/100);
            if(i<=page)
                ConvertToHtmlTable(dataTable, htmltable, builder, false, context);
            else
                ConvertToHtmlTable(dataTable, htmltable, builder, true, context);

        }
 
    }

    #endregion

  


   

    public StringBuilder ConvertToHtmlTable(DataTable dt, Table table, StringBuilder builder, bool end, HttpContext context)
      {
               if (dt.Rows.Count == 0)
               {
                    return null;//`enter code here`
               }

               if (table != null)
               {
                   foreach (DataRow r in dt.Rows)
                   {
                       builder.Append("<tr align='left' valign='top'>");
                       foreach (DataColumn c in dt.Columns)
                       {
                           builder.Append("<td align='left' valign='top'>");
                           builder.Append(r[c.ColumnName]);
                           builder.Append("</td>");
                       }
                       builder.Append("</tr>");
                   }
               }
               if (end)
               {
                   context.Response.Clear();
                   StringBuilder str1 = new StringBuilder();

                   str1.Append("<html>");
                   str1.Append("<head>");
                   str1.Append("<title>");
                   str1.Append("Page-");
                   str1.Append(Guid.NewGuid().ToString());
                   str1.Append("</title>");
                   str1.Append("</head>");
                   str1.Append("<body>");
                   str1.Append("<table border='1px' cellpadding='5' cellspacing='0' ");
                   str1.Append("style='border: solid 1px Silver; font-size: x-small;'>");
                   str1.Append("<th align='left' valign='top'>");
                   foreach (DataColumn c in dt.Columns)
                   {
                       str1.Append("<td align='left' valign='top'><b>");
                       str1.Append(c.ColumnName);
                       str1.Append("</b></td>");
                   }
                   str1.Append("</tr>");

                   str1.Append(builder);

                   str1.Append("</table>");
                   str1.Append("</body>");
                   str1.Append("</html>");

                  context.Response.ClearContent();
                  context.Response.ClearHeaders();
                  context.Response.BufferOutput = true;

                  context.Response.AddHeader("content-disposition", "attachment;filename=ExportData1.xls");
                  context.Response.Charset = "";
                  context.Response.ContentType = "application/vnd.xls";
                  context.Response.Write(str1);
                  // Response.Flush();
                  // Response.Close();
                  context.Response.End();

               }

            return builder;
       }


thank you
Pandiyan
Posted

1 solution

You can only send html to the client as part of a request. Your request just kicks off the thread, the thread itself is not running as part of an http request so can't write to the client, that includes downloading the file or showing a message or updating the html in any way. Basically you can't "push" things to the client, the client has to request them.

If you want some kind of progress bar you'll need to poll the server from the client to see if the task is done. Google for long running tasks with progress indicator for examples of what you need to do. Or you could look into SignalR as that framework is designed for this kind of task.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900