ExcelHelperクラス使用例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Core;
namespace ExcelHelper
{
class Program
{
static void Main(string[] args)
{
ExcelHelper eh = new ExcelHelper(@"c:\test.xls", "Sheet1");
eh.Operate = new Action<Excel.Worksheet>(OperateExcel);
eh.Execute();
Console.WriteLine("end ...");
}
static void OperateExcel(Excel.Worksheet worksheet)
{
Excel.Range range = (Excel.Range)worksheet.Cells[1, 1];
string cell = range.Text.ToString();
Console.WriteLine(cell);
}
}
}
ExcelHelperクラス
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Core;
namespace ExcelHelper
{
<summary>
</summary>
<remarks></remarks>
public class ExcelHelper
{
#region 変数・プロパティ
<summary>
</summary>
Excel.Application excelObject = null;
<summary>
</summary>
Excel.Workbook workBook = null;
<summary>
</summary>
Excel.Worksheet workSheet = null;
<summary>
</summary>
string fileName = string.Empty;
<summary>
</summary>
string sheetName = string.Empty;
<summary>
</summary>
public Action<Excel.Worksheet> Operate = null;
#endregion
#region コンストラクタ
<summary>
</summary>
private ExcelHelper()
{
}
<summary>
</summary>
<param name="fileName"></param>
<param name="sheetName"></param>
public ExcelHelper(string fileName, string sheetName)
{
this.fileName = fileName;
this.sheetName = sheetName;
}
#endregion
#region 指定されたワークシート名のインデックスを返すメソッド
<summary>
</summary>
<param name="sheetName"></param>
<param name="shs"></param>
<returns></returns>
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;
}
#endregion
#region オープン
<summary>
</summary>
private void Open()
{
this.excelObject = new Excel.Application();
this.excelObject.Visible = false;
this.workBook = (Excel.Workbook)(this.excelObject.Workbooks.Open(
this.fileName,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing
));
this.workSheet = (Excel.Worksheet)this.workBook.Sheets[this.GetSheetIndex(this.sheetName, this.workBook.Sheets)];
}
#endregion
#region クローズ
<summary>
</summary>
private void Close()
{
this.workBook.Close(Type.Missing, Type.Missing, Type.Missing);
this.excelObject.Quit();
}
#endregion
#region 実行
<summary>
</summary>
public void Execute()
{
try
{
this.Open();
this.Operate(this.workSheet);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
this.Close();
}
}
#endregion
}
}