Excelファイルを開き、指定のセル値を取得
public class ExcelUtil
{
#region メンバ変数
private Excel.Application oXls;
private Excel.Workbook oWBook;
#endregion
#region プロパティ
/// <summary>
/// ワークブック
/// </summary>
public Excel.Workbook Book
{
get { return this.oWBook; }
}
#endregion
/// <summary>
/// コンストラクタ
/// </summary>
public ExcelUtil()
{
}
#region メソッド
/// <summary>
/// 指定されたExcelファイルを開く
/// </summary>
/// <param name="fname">Excelファイル名</param>
public bool Open(string fname)
{
this.oXls = new Excel.Application();
this.oXls.DefaultFilePath = AppDomain.CurrentDomain.BaseDirectory;
//this.oXls.Visible = true; // 確認のためExcelのウィンドウを表示する
try
{
// Excelファイルをオープンする
this.oWBook = (Excel.Workbook)(oXls.Workbooks.Open(
fname, // オープンするExcelファイル名
Type.Missing, // (省略可能)UpdateLinks (0 / 1 / 2 / 3)
Type.Missing, // (省略可能)ReadOnly (True / False )
Type.Missing, // (省略可能)Format
// 1:タブ / 2:カンマ (,) / 3:スペース / 4:セミコロン (;)
// 5:なし / 6:引数 Delimiterで指定された文字
Type.Missing, // (省略可能)Password
Type.Missing, // (省略可能)WriteResPassword
Type.Missing, // (省略可能)IgnoreReadOnlyRecommended
Type.Missing, // (省略可能)Origin
Type.Missing, // (省略可能)Delimiter
Type.Missing, // (省略可能)Editable
Type.Missing, // (省略可能)Notify
Type.Missing, // (省略可能)Converter
Type.Missing, // (省略可能)AddToMru
Type.Missing, // (省略可能)Local
Type.Missing // (省略可能)CorruptLoad
));
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
}
/// <summary>
/// 指定されたワークシート名のWorksheetオブジェクトを返す
/// </summary>
/// <param name="sheetName">ワークシート名</param>
public Excel.Worksheet GetWorksheet(string sheetName)
{
Excel.Worksheet oSheet;
oSheet = (Excel.Worksheet)oWBook.Sheets[GetSheetIndex(sheetName, this.oWBook.Sheets)];
return oSheet;
}
/// <summary>
/// 指定されたワークシート名のインデックスを返すメソッド
/// </summary>
/// <param name="sheetName">ワークシート名</param>
/// <param name="shs">ワークシートコレクション</param>
private int GetSheetIndex(string sheetName, Excel.Sheets shs)
{
int i = 0;
foreach (Excel.Worksheet sh in shs)
{
if (sheetName == sh.Name)
{
return i + 1;
}
i += 1;
}
return 0;
}
/// <summary>
/// Excelファイルを閉じる
/// </summary>
public void Close()
{
this.oWBook.Close(Type.Missing, Type.Missing, Type.Missing);
//this.oXls.DefaultFilePath = @"C:\";
this.oXls.Quit();
Marshal.ReleaseComObject(this.oWBook);
Marshal.ReleaseComObject(this.oXls);
this.oWBook = null;
this.oXls = null;
}
#endregion
}
最終更新:2010年04月16日 15:22