.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Export Dataset data into excel

Posted By:Dhivakaran       Posted Date: November 29, 2010    Points: 50    Category: C#    URL: http://www.dotnetspark.com  

In this article I'm going to show how can export to dataset data into excel sheet.
 

 

Step1:

Create one class into your project and add below methods within your class.the below method I have passed two parameters. one is "result"in this argument we need to pass the dataset and another parameter name is "strName" in this argument we can specify(pass) the excel sheet name.

 public static void ExportToExcel(DataSet result, string strName)
       {
           HttpResponse response = HttpContext.Current.Response;
           response.Clear();
           response.Charset = "";
           response.ContentType = "application/vnd.xls";
           response.AddHeader("Content-Disposition", "attachment;filename=\"" + strName + "\"");
           if (result != null)
           {
               using (StringWriter sw = new StringWriter())
               {
                   using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                   {
                       // instantiate a datagrid
                       DataGrid dg = new DataGrid();
                       if (result != null && result.Tables[0].Rows.Count > 0)
                       {
                           dg.DataSource = result;
                           dg.DataBind();
                           dg.RenderControl(htw);
                       }
                       htw.WriteBreak();
                       response.Write(sw.ToString());
                       response.End();
                   }
               }
           }

       }

Steps 2:

Place button in your form "Export to excel" and within button click eventCreate one dataset object and assign some data into dataset as belo code.

dataset ds=new dataset();

ds=databasecontent();

// then pass this ds to export method like below

ExportToExcel(ds,"Sample");

 

 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend