using System.Runtime.InteropServices;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
string strMacroPath = @"C:\work\001 Excel シート名を 列挙する\Book1.xls";
try
{
object excelApp = CreateObject("Excel.Application");
excelApp.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, excelApp, new object[] { true });
object excelBooks = excelApp.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, excelApp, null);
object excelBook = excelBooks.GetType().InvokeMember
(
"Open"
, BindingFlags.InvokeMethod
, null
, excelBooks
, new object[]
{
strMacroPath
, 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
, 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);
System.Console.WriteLine(cnt);
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);
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 theException )
{
System.String errorMessage;
errorMessage = "Error: ";
errorMessage = System.String.Concat( errorMessage, theException.Message );
errorMessage = System.String.Concat( errorMessage, " Line: " );
errorMessage = System.String.Concat( errorMessage, theException.Source );
System.Console.WriteLine( errorMessage, "Error" );
}
}
<summary>
</summary>
<param name="progId"></param>
<param name="serverName">
</param>
<returns></returns>
public static object CreateObject(string progId, string serverName)
{
System.Type t;
if (serverName == null || serverName.Length == 0)
t = System.Type.GetTypeFromProgID(progId);
else
t = System.Type.GetTypeFromProgID(progId, serverName, true);
return System.Activator.CreateInstance(t);
}
<summary>
</summary>
<param name="progId"></param>
<returns></returns>
public static object CreateObject(string progId)
{
return CreateObject(progId, null);
}
}