Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Runtime.InteropServices;
- using System.Reflection;
- class Program
- {
- static void Main(string[] args)
- {
- //Excelファイルパス
- try
- {
- // Excel操作用COMオブジェクトを生成する
- System.Type t = System.Type.GetTypeFromProgID("Excel.Application");
- object excelApp = System.Activator.CreateInstance(t);
- // Excelファイルの表示
- excelApp.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, excelApp, new object[] { true });
- //警告メッセージをOFF
- excelApp.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, excelApp, new object[] { false });
- //ワークブックコレクションオブジェクトを生成する。
- object excelBooks = excelApp.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, excelApp, null);
- //Excelファイルのオープン
- object excelBook = excelBooks.GetType().InvokeMember
- (
- "Open"
- , BindingFlags.InvokeMethod
- , null
- , excelBooks
- , new object[]
- {
- args[0]
- , false
- , true
- , System.Type.Missing
- , System.Type.Missing
- , System.Type.Missing
- , System.Type.Missing
- , System.Type.Missing
- , System.Type.Missing
- , System.Type.Missing
- , System.Type.Missing
- , System.Type.Missing
- , System.Type.Missing
- }
- );
- object excelSheets = excelBook.GetType().InvokeMember("Worksheets", BindingFlags.GetProperty, null, excelBook, null);
- object cnt = excelSheets.GetType().InvokeMember("Count", BindingFlags.GetProperty, null, excelSheets, null);
- for (int i=1;i<=System.Convert.ToInt32(cnt);i++)
- {
- object sheet = excelSheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, excelSheets, new object[1]{i});
- object sheetName = sheet.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, sheet, null);
- System.Console.WriteLine(sheetName);
- }
- //閉じる
- excelApp.GetType().InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, excelApp, null);
- //COM解放
- System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelBook);
- excelBook = null;
- System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelBooks);
- excelBooks = null;
- System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelApp);
- excelApp = null;
- }
- catch(System.Exception ex)
- {
- System.Console.WriteLine(ex.Message, "Error" );
- }
- }
- }
Add Comment
Please, Sign In to add comment