Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 4th, 2012  |  syntax: None  |  size: 2.67 KB  |  hits: 20  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. What's the easiest way to create an Excel table with C#?
  2. ApplicationClass myExcel;
  3. try
  4. {
  5. myExcel = GetObject(,"Excel.Application")
  6. }
  7. Catch (Exception ex)
  8. {
  9. myExcel = New ApplicationClass()
  10. }
  11.  
  12. myExcel.Visible = true;
  13. Workbook wb1 = myExcel.Workbooks.Add("");
  14. Worksheet ws1 = (Worksheet)wb1.Worksheets[1];
  15.  
  16. //Read the connection string from App.Config
  17. string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["NewConnString"].ConnectionString;
  18.  
  19. //Open a connection to the database
  20. SqlConnection myConn = new SqlConnection();
  21. myConn.ConnectionString = strConn;
  22. myConn.Open();
  23.  
  24. //Establish the query
  25. SqlCommand myCmd = new SqlCommand("select * from employees", myConn);
  26. SqlDataReader myRdr = myCmd.ExecuteReader();
  27.  
  28. //Read the data and put into the spreadsheet.
  29. int j = 3;
  30. while (myRdr.Read())
  31. {
  32. for (int i=0 ; i < myRdr.FieldCount; i++)
  33. {
  34. ws1.Cells[j, i+1] = myRdr[i].ToString();
  35. }
  36. j++;
  37. }
  38.  
  39. //Populate the column names
  40. for (int i = 0; i < myRdr.FieldCount ; i++)
  41. {
  42. ws1.Cells[2, i+1] = myRdr.GetName(i);
  43. }
  44. myRdr.Close();
  45. myConn.Close();
  46.  
  47. //Add some formatting
  48. Range rng1 = ws1.get_Range("A1", "H1");
  49. rng1.Font.Bold = true;
  50. rng1.Font.ColorIndex = 3;
  51. rng1.HorizontalAlignment = XlHAlign.xlHAlignCenter;
  52.  
  53. Range rng2 = ws1.get_Range("A2", "H50");
  54. rng2.WrapText = false;
  55. rng2.EntireColumn.AutoFit();
  56.  
  57. //Add a header row
  58. ws1.get_Range("A1", "H1").EntireRow.Insert(XlInsertShiftDirection.xlShiftDown, Missing.Value);
  59. ws1.Cells[1, 1] = "Employee Contact List";
  60. Range rng3 = ws1.get_Range("A1", "H1");
  61. rng3.Merge(Missing.Value);
  62. rng3.Font.Size = 16;
  63. rng3.Font.ColorIndex = 3;
  64. rng3.Font.Underline = true;
  65. rng3.Font.Bold = true;
  66. rng3.VerticalAlignment = XlVAlign.xlVAlignCenter;
  67.  
  68. //Save and close
  69. string strFileName = String.Format("Employees{0}.xlsx", DateTime.Now.ToString("HHmmss"));
  70. System.IO.File.Delete(strFileName);
  71. wb1.SaveAs(strFileName, XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlExclusive, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value);
  72. myExcel.Quit();
  73.        
  74. Excel table with Named area "MyData"
  75. Name, FamilyName, Birthday
  76.  
  77. open System.Data.OleDb.OleDbConnection
  78. execute sql "Insert into MyData(Name, FamilyName, Birthday) values(...)"
  79.        
  80. private const string FORMAT_EXCEL_CONNECT =
  81.         // @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR={1}""";
  82.         @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;HDR={1}""";
  83.  
  84.  
  85.     private static string GetExcelConnectionString(string excelFilePath, bool header)
  86.     {
  87.         return string.Format(FORMAT_EXCEL_CONNECT,
  88.             excelFilePath,
  89.             (header) ? "Yes" : "No"
  90.             );
  91.     }