Pages

Thursday, November 28, 2013

Export To XLS

protected void Page_Load(object sender, EventArgs e)
    {
     
               try
               {

                   SqlDataAdapter da = new SqlDataAdapter("Select * from Features", "Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=;");
                   DataSet ds = new DataSet();
                   da.Fill(ds);

                 
                   string date = string.Format("{0:dd-MM-yyyy}", DateTime.Now);
                   string strFileName = "Test";
                   string path = strFileName  + "_" + date + ".xls";


                   Directory.SetCurrentDirectory(Server.MapPath("~/"));// Changed the default location of the storage of the file.
                   StreamWriter sw = File.AppendText(Path.Combine(strFileName + "_" + date + ".xls")); //Append the file name with the file path.
                   for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                   {

                       sw.AutoFlush = true;
                       sw.Write(ds.Tables[0].Columns[i].ToString() + "\t");
                   }
                   sw.Write("\n");
                   for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                   {
                       for (int x = 0; x < ds.Tables[0].Columns.Count; x++)
                       {
                           sw.Write(ds.Tables[0].Rows[i][ds.Tables[0].Columns[x].ToString()].ToString() + "\t");
                       }
                       sw.Write("\n");
                   }

                   sw.Write("\n");
               }

               catch (Exception)
               {

                   throw;
               }
               finally
               {

                 
               }
    }

No comments:

Post a Comment