title: Appending data from database to Excel in Asp.Net
body: <p>I have developed an application in which I have to insert data from database to Excel, the size of inserting data is predefined.</p>
  
  <p>Suppose there are 20 records of any city. Now at first I have to insert only 5 records then after viewing some message to user next 5 data will append to the same Excel file and so on.</p>
  
  <p>Following is my code to insert data to Excel and the size is defined in the Web.Config file.</p>
  
  <p>Web.Config Code:</p>
  
  <pre><code>&lt;appSettings&gt;
    &lt;add key="UserRecord" value="6"/&gt;
  &lt;/appSettings&gt;
  </code></pre>
  
  <p>Code:</p>
  
  <pre><code>public void InsertRecordToExcel()
      {
          DAL ObjDal = new DAL();
          string record = ConfigurationManager.AppSettings["UserRecord"];
          try
          {
              int n = Convert.ToInt32(record);
              string filename = Server.MapPath("UserDataSheet");
              string City = TxtCityName.Text;
              DataTable dt = new DataTable();
              dt = ObjDal.GetData(City);
              while(dt.Rows.Count&gt;0)
              {
                  StringWriter writer = new StringWriter();
                  HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
                  GridView gridView = new GridView();
                  DataTable dtn = new DataTable();
                  gridView.DataSource = dt.AsEnumerable().Take(n).CopyToDataTable();
                  gridView.AutoGenerateColumns = true;
                  gridView.DataBind();
                  gridView.RenderControl(htmlWriter);
                  htmlWriter.Close();
                  Response.Clear();
                  Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls");
                  Response.Charset = "";
                  Response.Write(writer.ToString());
                  Response.End();
                  LblMessage.Text = n + " " + "Record Added Successfully";
              }                
          }
  
          catch (Exception ex)
          {
              throw ex;
          }
      }
  </code></pre>
  
  <p>What is the procedure of appending a data to the Excel file?</p>