(C#)Excelファイルを読み書きする
作ったもの
Excel ファイルの読み書きには、NPOI というライブラリが便利です。ファイル入出力やセルのアクセスをできるだけ短く記述できるように、クラスを作成しました。
前提
- Visual Studio 上で、パッケージマネージャーコンソールを開く。(Alt, T, N, O)
- PM> Install-Package npoi と入力して、NPOI をインストール。
- using NPOI.SS.UserModel;
- using NPOI.XSSF.UserModel;
- using System.IO;
- NPOI の関数のリファレンスを調べる。例:NPOI入門してみた - かずきのBlog@hatena
コード
/// <summary> /// Excelファイルを読むためのクラス /// </summary> class Excel { private IFormulaEvaluator _eval = null; private IWorkbook _book = null; private ISheet _sheet = null; /// <summary> /// 新規Excelファイルを開く。 /// </summary> public Excel() { _book = new XSSFWorkbook(); _sheet = _book.CreateSheet("Sheet1"); _eval = _book.GetCreationHelper().CreateFormulaEvaluator(); } /// <summary> /// Excelファイルを読み込む。 /// </summary> /// <param name="path">Excelファイルのパス</param> public Excel(string path) { Read(path); } /// <summary> /// Excelファイルを読み込む。 /// </summary> /// <param name="path">Excelファイルのパス</param> public void Read(string path) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { _book = WorkbookFactory.Create(fs, ImportOption.All); } _eval = _book.GetCreationHelper().CreateFormulaEvaluator(); _sheet = _book.GetSheetAt(0); } /// <summary> /// Excelファイルを書き込む。 /// </summary> /// <param name="path">Excelファイルのパス</param> public void Write(string path) { using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)) { _book.Write(fs); } } /// <summary> /// 読み書きするシートを変更する。 /// </summary> /// <param name="idx">シートの番号 0,1,2...</param> public void ChangeSheet(int idx) { _sheet = _book.GetSheetAt(idx); _y = -1; _row = null; } /// <summary> /// シートの行数 /// </summary> public int NumRow { get { return _sheet.LastRowNum - 1; } } private int _y = -1; private IRow _row = null; /// <summary> /// ある行の列数 /// </summary> /// <param name="y">何行目</param> public int Width(int y) { var row = _y == y ? _row : _sheet.GetRow(y); _y = y; _row = row; return row == null ? 0 : row.LastCellNum - 1; } /// <summary> /// セルを取得。なければnull /// </summary> /// <param name="y">行</param> /// <param name="x">列</param> public ICell GetCell(int y, int x) { var row = _y == y ? _row : _sheet.GetRow(y); _y = y; _row = row; return row == null ? null : row.GetCell(x); } /// <summary> /// セルの内容を文字列で取得。なければ"" /// </summary> /// <param name="y">行</param> /// <param name="x">列</param> public string GetString(int y, int x) { var cell = GetCell(y, x); return CellToString(cell); } /// <summary> /// セルを取得。なければ新規に作成される。 /// </summary> /// <param name="y">行</param> /// <param name="x">列</param> public ICell CreateCell(int y, int x) { var cell = GetCell(y, x); if (cell != null) return cell; _row = _sheet.GetRow(y) ?? _sheet.CreateRow(y); return _row.GetCell(x) ?? _row.CreateCell(x); } /// <summary> /// セルを評価する。 /// </summary> public CellValue Evaluate(ICell cell) { return _eval.Evaluate(cell); } /// <summary> /// セルの内容を文字列にする。 /// </summary> private string CellToString(ICell cell) { if (cell == null) { return ""; } if (cell.CellType != CellType.Formula) { switch (cell.CellType) { case CellType.Blank: return ""; case CellType.Boolean: return cell.BooleanCellValue.ToString(); case CellType.Error: return cell.ErrorCellValue.ToString(); case CellType.Numeric: return cell.NumericCellValue.ToString(); case CellType.String: return cell.StringCellValue; default: return ""; } } var value = Evaluate(cell); switch (value.CellType) { case CellType.Blank: return ""; case CellType.Boolean: return value.BooleanValue.ToString(); case CellType.Error: return value.ErrorValue.ToString(); case CellType.Numeric: return value.NumberValue.ToString(); case CellType.String: return value.StringValue; default: return ""; } }
使い方(新規作成するとき)
Excel excel = new Excel(); // ブックの新規作成 ICell cell = excel.CreateCell(0, 3); // セルの作成(第0行3列) cell.SetCellValue("セルの内容"); // そのセルの編集 excel.Write(@"C:\Users\ユーザー名\Desktop\xls.xlsx"); // ブックに書き出し
使い方(読み込むとき)
Excel excel = new Excel(@"C:\Users\ユーザー名\Desktop\xls.xlsx"); // ブックの読み込み ICell cell = excel.GetCell(2, 3); // セルの取得(第2行3列) string s = excel.GetString(1, 2); // セルを文字列として取得(第1行2列)