Tag: CSharp Office連携
参考情報†
EXCELを操作する†
EXCELシートに含まれるマクロを実行する例†
public static object CreateObject(string progId, string serverName)
{
Type t;
if (serverName == null || serverName.Length == 0)
t = Type.GetTypeFromProgID(progId);
else
t = Type.GetTypeFromProgID(progId, serverName, true);
if (t == null)
{
return null;
}
return Activator.CreateInstance(t);
}
public static object CreateObject(string progId)
{
return CreateObject(progId, null);
}
private static void ShowError(Exception ex)
{
string title = ex.Message;
string content = ex.Message;
if (ex.InnerException != null)
{
content = ex.InnerException.Message;
}
MessageBox.Show(content, title);
}
public static void RunMacro(string xlsPath, string macroName, string argFileName)
{
// 指定されたマクロに引数を渡して起動するメソッド(今回はボツ)
object excel = null;
object books = null;
object book = null;
try
{
// Excel操作用COMオブジェクトを生成する
excel = CreateObject("Excel.Application");
if (excel == null)
{
throw new ApplicationException("Excelのインスタンス生成に失敗しました");
}
//ワークブックコレクションオブジェクトを生成する。
books = excel.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, excel, null);
//Excelファイルのオープン
book = books.GetType().InvokeMember(
"Open", BindingFlags.InvokeMethod, null,
books, new object[] {
xlsPath
, Type.Missing
, Type.Missing
, Type.Missing
, Type.Missing
, Type.Missing
, Type.Missing
, Type.Missing
, Type.Missing
, Type.Missing
, Type.Missing
, Type.Missing
, Type.Missing
});
// Excelファイルの表示
excel.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, excel, new object[] { true });
//マクロ実行(Testというサブプロシージャを実行する)
excel.GetType().InvokeMember("Run", BindingFlags.InvokeMethod, null, excel, new object[] { macroName, argFileName });
//閉じる
excel.GetType().InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, excel, null);
}
catch (Exception ex)
{
ShowError(ex);
}
finally
{
if (book != null)
{
Marshal.FinalReleaseComObject(book);
book = null;
}
if (books != null)
{
Marshal.FinalReleaseComObject(books);
books = null;
}
if (excel != null)
{
Marshal.FinalReleaseComObject(excel);
excel = null;
}
}
}