Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. using System;
  2. using System.Data;
  3. using Microsoft.Office.Interop.Excel;
  4. using Application = Microsoft.Office.Interop.Excel.Application;
  5. using DataTable = System.Data.DataTable;
  6.  
  7.  
  8. [STAThread]
  9. static void Main()
  10. {
  11. Application xlApp = null;
  12.  
  13. try
  14. {
  15. xlApp = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
  16. }
  17. catch (Exception)//Excel not open
  18. {
  19. return;
  20. }
  21.  
  22. xlApp.Visible = true;
  23.  
  24. var wb = xlApp.ActiveWorkbook;
  25.  
  26. Worksheet ws = null;
  27.  
  28. try
  29. {
  30. ws = (Worksheet)wb.Worksheets["SomeSheet"];
  31. }
  32. catch (Exception e)
  33. {
  34. return;
  35. }
  36.  
  37. if (ws == null)
  38. {
  39. return;
  40. }
  41.  
  42. var dt = new DataTable();
  43.  
  44. dt = new DataTable();
  45. dt.Clear();
  46. dt.Columns.Add("Col1");
  47. dt.Columns.Add("Col2");
  48. for (int ii = 0; ii < 20; ii++)
  49. {
  50. DataRow row = dt.NewRow();
  51. row["Col1"] = "xxxx";
  52. row["Col2"] = "yyyy";
  53. dt.Rows.Add(row);
  54. }
  55.  
  56. //Header
  57. for (int i = 0; i < dt.Columns.Count; i++)
  58. {
  59. ws.Cells[1, i + 1] = dt.Columns[i].ColumnName;
  60.  
  61. }
  62.  
  63. //Data
  64. for (int i = 0; i < dt.Rows.Count; i++)
  65. {
  66. for (int j = 0; j < dt.Columns.Count; j++)
  67. {
  68. ws.Cells[i + 2, j + 1] = dt.Rows[i][j];
  69. }
  70. }
  71.  
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement