Guest
Public paste!

scmay

By: a guest | Aug 5th, 2009 | Syntax: C# | Size: 1.90 KB | Hits: 103 | Expires: Never
Copy text to clipboard
  1. private void SaveToExcel(IList personList)
  2.         {
  3.            
  4.             //Make sure folder where the template lies  has full permission
  5.  
  6.             //This lets you know what user is running the system
  7.             Debug.Print(Environment.UserDomainName + "\\" + Environment.UserName);
  8.  
  9.             string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" +            System.Configuration.ConfigurationManager.AppSettings["ExcelPath"] + ";Extended Properties=" + (char)34 + "Excel 8.0;HDR=Yes;" + (char)34;
  10.  
  11.             if (File.Exists(System.Configuration.ConfigurationManager.AppSettings["ExcelFilePath"]))
  12.                 File.Delete(System.Configuration.ConfigurationManager.AppSettings["ExcelFilePath"]);
  13.  
  14.             DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
  15.  
  16.             using (DbConnection connection = factory.CreateConnection())
  17.             {
  18.                 connection.ConnectionString = connectionString;
  19.                 connection.Open();
  20.  
  21.                 using (DbCommand command = connection.CreateCommand())
  22.                 {
  23.                     command.CommandText = "CREATE TABLE Person (ID char(255), Name char(255), Age char(255))";
  24.  
  25.                     command.ExecuteNonQuery();
  26.  
  27.                     foreach(IPerson person in personList )
  28.                     {
  29.                         command.CommandText = "INSERT INTO Person (ID, Name, Age ) VALUES('" + person.ID + "','" + person.Name + "','" + person.Age + "') ";
  30.  
  31.                         command.ExecuteNonQuery();
  32.                     }
  33.                  
  34.  
  35.                 }
  36.                 connection.Close();
  37.             }
  38.             view.Write("<script language=\"Javascript\">window.open('OpenFile.aspx?fn=" +       System.Configuration.ConfigurationManager.AppSettings["ExcelFilePath"].Replace("\\", "\\\\") +
  39.                       "',\"ExcelExport\");</script>");
  40.         }