Guest User

Untitled

a guest
Sep 26th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.99 KB | None | 0 0
  1. using System.Runtime.InteropServices;
  2. using System.Reflection;
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. //Excelファイルパス
  8. try
  9. {
  10. // Excel操作用COMオブジェクトを生成する
  11. System.Type t = System.Type.GetTypeFromProgID("Excel.Application");
  12. object excelApp = System.Activator.CreateInstance(t);
  13.  
  14. // Excelファイルの表示
  15. excelApp.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, excelApp, new object[] { true });
  16.  
  17. //警告メッセージをOFF
  18. excelApp.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, excelApp, new object[] { false });
  19.  
  20. //ワークブックコレクションオブジェクトを生成する。
  21. object excelBooks = excelApp.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, excelApp, null);
  22.  
  23. //Excelファイルのオープン
  24. object excelBook = excelBooks.GetType().InvokeMember
  25. (
  26. "Open"
  27. , BindingFlags.InvokeMethod
  28. , null
  29. , excelBooks
  30. , new object[]
  31. {
  32. args[0]
  33. , false
  34. , true
  35. , System.Type.Missing
  36. , System.Type.Missing
  37. , System.Type.Missing
  38. , System.Type.Missing
  39. , System.Type.Missing
  40. , System.Type.Missing
  41. , System.Type.Missing
  42. , System.Type.Missing
  43. , System.Type.Missing
  44. , System.Type.Missing
  45. }
  46. );
  47.  
  48. object excelSheets = excelBook.GetType().InvokeMember("Worksheets", BindingFlags.GetProperty, null, excelBook, null);
  49. object cnt = excelSheets.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, excelSheets, null);
  50. for (int i=1;i<=System.Convert.ToInt32(cnt);i++)
  51. {
  52. object sheet = excelSheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, excelSheets, new object[1]{i});
  53. object sheetName = sheet.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, sheet, null);
  54. System.Console.WriteLine(sheetName);
  55. }
  56.  
  57. //閉じる
  58. excelApp.GetType().InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, excelApp, null);
  59.  
  60. //COM解放
  61. System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelBook);
  62. excelBook = null;
  63.  
  64. System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelBooks);
  65. excelBooks = null;
  66.  
  67. System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelApp);
  68. excelApp = null;
  69. }
  70. catch(System.Exception ex)
  71. {
  72. System.Console.WriteLine(ex.Message, "Error" );
  73. }
  74. }
  75. }
Add Comment
Please, Sign In to add comment