8

I tried to export the dataset which have 4 tables to the excel sheet, Unfortunately I can't. I have code to export data table to excel. So instead of dataset, I called the "ExportToExcel" function which I have in my code to export datatable to excel 4 times. But once it created the first sheet, it stops the control flow. Control doesn't call the second function ("ExportToExcel(dsResult.Tables[2], "AthleteSentCount");") Here is the code

protected void ExportToExcel(object sender, EventArgs e)
{
     ExportToExcel(dsResult.Tables[3], "AthleteInboxCount");
     ExportToExcel(dsResult.Tables[2], "AthleteSentCount");
     ExportToExcel(dsResult.Tables[0], "CoachInboxCount");
     ExportToExcel(dsResult.Tables[1], "CoachSentCount");
}

void ExportToExcel(DataTable dt, string FileName)
{
    if (dt.Rows.Count > 0)
    {
        string filename = FileName + ".xls";
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        DataGrid dgGrid = new DataGrid();
        dgGrid.DataSource = dt;
        dgGrid.DataBind();

        //Get the HTML for the control.
        dgGrid.RenderControl(hw);
        //Write the HTML back to the browser.
        //Response.ContentType = application/vnd.ms-excel;
        Response.ContentType = "application/vnd.ms-excel";
        Response.AppendHeader("Content-Disposition", 
                              "attachment; filename=" + filename + "");
        this.EnableViewState = false;
        Response.Write(tw.ToString());
        Response.End();
    }
}

If any body knows to export the dataset to the excel with the bar chart please help me. Else please give your solution to the problem.

6
  • what issue u r getting in this? Commented Oct 15, 2013 at 6:00
  • Thanks for your response. Control stops its operation once it creates its first excel sheet ie once the "ExportToExcel(dsResult.Tables[3], "AthleteInboxCount");" function got excecuted Commented Oct 15, 2013 at 6:01
  • ys why not?try to pass datatabe in a loop till Data Set length Commented Oct 15, 2013 at 6:03
  • I tried, but it stops the flow after "Response.End();" method while executing the first loop Commented Oct 15, 2013 at 6:11
  • remove Response.End(). it will work Commented Oct 15, 2013 at 6:15

4 Answers 4

4

First of all your function start streaming content

 Response.ContentType = "application/vnd.ms-excel";
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");

to end user and END it with

Response.End();

Moreover if you fix this your code will product 4 excel files.

There is an existing code for creating Excel sheets on stack overflow: How to add additional worksheets to an Excel from DataTable The only change you will have to made will be saving xlsx to stream and transmit this stream to user.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you @Garath, your post is very useful to me. I have to made some little changes like syntax. But it works great. Again thanks.
Can I know why the control stops when it creates the first sheet in the above code?
@ArunKumarT the code not excatly stops, but because you call Response.End(); the rest of code is not send to end user.
1

Written in WCF & ASMX


But I used EPPuls. dlll file its Open Source dll. Please check below link for Reference. http://epplus.codeplex.com/.

Code :

string excelFileName = @"E:\GOPI_16122016.xls";
 DataTable dt = ds.Tables[0];
 string worksheetsName = "Report";
 ExcelPackage pack = new ExcelPackage();
 ExcelWorksheet wrkSht = pack.Workbook.Worksheets.Add(worksheetsName);
 wrkSht.Cells["A1"].LoadFromDataTable(dt, true);
 pack.SaveAs(new FileInfo(excelFileName));
  MailMessage msg = new MailMessage();
                msg.To.Add(new MailAddress("[email protected]", "GOPIKRISHNA"));

                msg.From = new MailAddress("[email protected]", "Domain");
                msg.Subject = "REPORTS";
                string str = "Dear Team,<br/> Please find the Reports Details <br/><br/>";
                Attachment attachment = new System.Net.Mail.Attachment(excelFileName);
                msg.Attachments.Add(attachment);
                msg.Body = str ;
                msg.IsBodyHtml = true;
                SmtpClient client = new SmtpClient();
                client.UseDefaultCredentials = false;
                client.Credentials = new System.Net.NetworkCredential("[email protected]", "");
                client.Port = 25; // You can use Port 25 if 587 is blocked (mine is!)
                client.Host = "[email protected]";
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.EnableSsl = true;
                client.Send(msg);

1 Comment

If you could elaborate a bit more on your answer, clean up the code, and adapt it a bit to the specific case of downloading an excel file rather than e-mail it (i.e. the Response part), I think you would not only help the OP but also many other people. EPPlus is SO much powerful and simple than many other alternatives
0

You are welcome to download and use my free C# library to export a DataSet to a "real" Excel .xlsx file.

It uses the Microsoft OpenXML libraries, and takes just one line of code.

Export to Excel

It looks like your code is for an ASP.Net web application, so using my library, your code would just look like this:

protected void ExportToExcel(object sender, EventArgs e)
{
    CreateExcelFile.CreateExcelDocument(dsResult, "YourExcelfilename.xlsx", Response);
}

Just one line of code, and you'll get a real Excel file written to your page's Response.

It will contain one Worksheet per DataTable in your DataSet.

Comments

0

Here is some souce code sample about how to export dataset to Excel. You can use ExcelWorksheet.easy_insertDataSet method to insert multiple datatables.

About the other question, check this code for bar chart and adjust the code to generate bar chart like this:

xlsChart.easy_setChartType(Chart.CHART_TYPE_BAR_CLUSTERED);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.