[Excelブックに変換]IEnumerableをClosedXMLを使ってEXCELブックに変換する。#ClosedXML #ExtensionMethod
using System.Collections.Generic;
using System.Linq;
using ClosedXML.Excel;
namespace ClassLibrary.Extensions
{
public static class IEnumerableExtention
{
public static void ToExcel<T>(this IEnumerable<T> enumerable,
string path, string sheetName = "Sheet1")
{
// Excelブックを作成
var book = new XLWorkbook();
// シートを作成
var sheet = book.Worksheets.Add(sheetName);
// Tタイプのプロパティを記録
var props = typeof(T).GetProperties().ToList();
// 行件数
var rowCount = 1;
// ヘッダにあたる行を作成
{
// 行を取得
var row = sheet.Row(rowCount++);
// ヘッダ列の値を設定
for (var i = 1; i <= props.Count; i++)
{
row.Cell(i).Value = props[i - 1].Name;
}
}
// データ出力
foreach (var obj in enumerable)
{
// データセットする行を取得
var row = sheet.Row(rowCount++);
// 各プロパティの値をセット
for (var i = 1; i <= props.Count; i++)
{
var prop = props[i - 1];
vara val = prop.GetValue(obj);
if (val is string)
{
row.Cell(i).Value = "'" + val;
}
else
{
row.Cell(i).Value = val;
}
}
}
// テーブルを作成
sheet.Range(1, 1, rowCount - 1, props.Count).CreateTable();
// セルの幅をコンテンツの内容にあわせてリサイズ
sheet.Columns(1, props.Count).AdjustToContents();
// 保存
book.SaveAs(path);
}
}
}