|
■No88664 (夜叉丸 さん) に返信
> 指定したエクセルファイルの指定シートを開きたいのですが、
public static void OpenExcel(string excelFile, string sheetName = null)
{
dynamic app = null;
dynamic books = null;
dynamic book = null;
dynamic sheets = null;
dynamic sheet = null;
try
{
app = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
app.Visible = true;
books = app.Workbooks;
book = books.Open(excelFile);
if (!string.IsNullOrEmpty(sheetName))
{
sheets = book.Sheets;
sheet = sheets[sheetName];
sheet.Select();
}
}
finally
{
Release(ref sheet);
Release(ref sheets);
Release(ref book);
Release(ref books);
Release(ref app, true);
}
}
private static void Release<T>(ref T comObject, bool force = false) where T : class
{
if (comObject != null)
{
if (Marshal.IsComObject(comObject))
{
if (force)
{
Marshal.FinalReleaseComObject(comObject);
}
else
{
Marshal.ReleaseComObject(comObject);
}
}
comObject = default(T);
}
}
|