Exporting Data From ASP.NET Application To CSV File

In the Previous Article we saw how to export data to an excel sheet through ASP.NET application without using any external DLLs.

Here is the tag where you can find all the Export Data Articles.

In this article we will see how to export the same data to CSV file using the same technique and not using any external libraries.

Here I will walk you through the code for exporting data in Excel sheet in ASP.NET.

Download source code here.

Everything is same as exporting data into an excel sheet.

Below is the code you can have a look and then I will discuss every bit of it for your understanding.
  protected void ExportToCSV(object sender, EventArgs e)
  {
      DataTable dt = GetData();

      Response.Clear();
      Response.Buffer = true;
      Response.AddHeader("content-disposition", "attachment;filename=MyReport.csv");
      Response.Charset = "";
      Response.ContentType = "application/text";


      StringBuilder sb = new StringBuilder();
      for (int k = 0; k < dt.Columns.Count; k++)
      {
          //add separator
          sb.Append(dt.Columns[k].ColumnName + ',');
      }
      //append new line
      sb.Append("\r\n");
      for (int i = 0; i < dt.Rows.Count; i++)
      {
          for (int k = 0; k < dt.Columns.Count; k++)
          {
              //add separator
              sb.Append(dt.Rows[i][k].ToString().Replace(",", ";") + ',');
          }
          //append new line
          sb.Append("\r\n");
      }
      Response.Output.Write(sb.ToString());
      Response.Flush();
      Response.End();
  }
I guess this must be very clear to everyone what I have written inside. Anyway let's discuss it here.

  1. First, I get the data source from the method GetData(), which is nothing but just a method that returns a datatable with some data inside it. You can have your own dataset here from DB or wherever you want.
  2. Second, I have taken a grid view so that I can render that data in it. If you have a grid view at your page level then no need to take one and bind it here, even you need not to get the data again if you have already that data rendered in any gridview or what in your page.
  3. Third, Add Response headers, content types for Excel download. Remember the Content Type is very important, this is code which decides the file type you are downloading. So here for CSV file download the content Type is "attachment;filename=MyReport.csv". Also give name to the file you are downloading.
  4. Fourth, Get a string builder and run a loop to create a comma delimited string.
  5. Fifth, Now write the string builder value into response object and you are all set to download the excel sheet.
If you are looking for the GetData() method to test out the feasibility of this process of exporting data into excel sheet in ASP.NET and C# then here is it.
     private DataTable GetData()
     {
         // Here we create a DataTable with four columns.
         DataTable dtSample = new DataTable();
         dtSample.Columns.Add("Dosage", typeof(int));
         dtSample.Columns.Add("Drug", typeof(string));
         dtSample.Columns.Add("Patient", typeof(string));
         dtSample.Columns.Add("Date", typeof(DateTime));

         // Here we add five DataRows.
         dtSample.Rows.Add(25, "Indocin", "David", DateTime.Now);
         dtSample.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
         dtSample.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
         dtSample.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
         dtSample.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
         dtSample.Rows.Add(25, "Indocin", "David", DateTime.Now);
         dtSample.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
         dtSample.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
         dtSample.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
         dtSample.Rows.Add(25, "Indocin", "David", DateTime.Now);
         dtSample.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
         dtSample.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
         dtSample.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
         dtSample.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
         dtSample.Rows.Add(25, "Indocin", "David", DateTime.Now);
         
         return dtSample;

     }
Hope this article helps you, as this method helped me a lot to overcome the unnecessary usage of external dll for exporting data into excel sheets.

Demo:

Export Data From ASP.NET



No comments:

Post a Comment