redwarrior’s diary

C#, ASP.NET, WEB, G*などの雑多な情報

Excel読込でNPOIをEPPlusのように使うため拡張メソッドを作成した

なぜEPPlusを直接使わないかは、過去の記事を参照。

redwarrior.hateblo.jp

NPOIを直接使うと、同じようなコーディングを繰り返し行う事が結構あったので、拡張メソッドを作成しました。
EPPlusを参考にしたメソッドや、あると便利そうなメソッドを作りました。

public static class NPOIExtension
{
    //GetCell("K21")のようにセルを指定できる
    public static ICell GetCell(this ISheet sheet, string cellRef)
    {
        var cellReference = new CellReference(cellRef);
        return sheet.GetRow(cellReference.Row).GetCell(cellReference.Col);
    }

    //GetCellRange("A3:F80")のようにセルの範囲を指定できる
    public static IList<ICell> GetCellRange(this ISheet sheet, string rangeRef)
    {
        var cells = new List<ICell>();
        var cellRangeAddress = CellRangeAddress.ValueOf(rangeRef);
        for (var i = cellRangeAddress.FirstRow; i <= cellRangeAddress.LastRow; i++)
        {
            for (var j = cellRangeAddress.FirstColumn; j <= cellRangeAddress.LastColumn; j++)
            {
                var cell = sheet.GetRow(i).GetCell(j);
                cells.Add(cell);
            }
        }

        return cells;
    }

    //Cellの値が空の場合は、0ではなくnullを返し、それ以外は int を返すメソッド
    public static int? IntOrNull(this ICell cell)
    {
        switch (cell.CellType)
        {
            case CellType.Formula:
            case CellType.Numeric:
                //NumericCellValueプロパティの取得時に関数が評価される
                //関数の評価結果は、数値として扱う
                return Convert.ToInt32(cell.NumericCellValue);
            case CellType.Blank:
                return null;
            default:
                throw new ArgumentOutOfRangeException();
        }
    }

    //Cellの値が空の場合は、0ではなくnullを返し、それ以外は decimal を返すメソッド
    public static decimal? DecimalOrNull(this ICell cell)
    {
        switch (cell.CellType)
        {
            case CellType.Formula:
            case CellType.Numeric:
                //NumericCellValueプロパティの取得時に関数が評価される
                //関数の評価結果は、数値として扱う
                return Convert.ToDecimal(cell.NumericCellValue);
            case CellType.Blank:
                return null;
            default:
                throw new ArgumentOutOfRangeException();
        }
    }
}

以上です。