初心者です。今、ClosedXMLを使用してExcelファイルの表の作成をしています。
ピボットテーブルでは作成してみたので今回は別のやり方でExcelファイルを作っています。
表の出力がうまくいきません。
重複した名前を1つだけ表示し金額も適切なところに表示されるようにしたい。
今後、罫線、名前の下に「合計」と表示、年月の隣に「合計」と表示、行合計、列合計を表示したいのですが、データを追加する予定なので最終の行と列が分からない状態の設定方法を知りたいです。
※出力されたExcelファイル
名前 コード 2019年4月 2019年5月 2019年6月 2019年7月 2020年4月
Croissant 1 150
Croissant 1 200
Doughnut 2 250
Bearclaw 3 134
Danish 4 394
Scone 5 135
Croissant 1 250
Doughnut 2 225
Bearclaw 3 184
Danish 4 190
Scone 5 122
Croissant 1 134
Doughnut 2 210
Bearclaw 3 124
Danish 4 221
Scone 5 243
test 6 777
test 6 250
ソース
public class Pastry
{
public Pastry(string code, string name, int amount, string yearMonth)
{
Code = code;
Name = name;
NumberOfOrders = amount;
YearMonth = yearMonth;
}
public string Code { get; set; }
public string Name { get; set; }
public int NumberOfOrders { get; set; }
public string YearMonth { get; set; }
}
pastries = new List
{
new Pastry("1","Croissant", 150, "2019年4月"),
new Pastry("1","Croissant", 200, "2019年4月"),
new Pastry("1","Croissant", 250, "2019年5月"),
new Pastry("1","Croissant", 134, "2019年6月"),
new Pastry("2","Doughnut", 250, "2019年4月"),
new Pastry("2","Doughnut", 225, "2019年5月"),
new Pastry("2","Doughnut", 210, "2019年6月"),
new Pastry("3","Bearclaw", 134, "2019年4月"),
new Pastry("3","Bearclaw", 184, "2019年5月"),
new Pastry("3","Bearclaw", 124, "2019年6月"),
new Pastry("4","Danish", 394, "2019年4月"),
new Pastry("4","Danish", 190, "2019年5月"),
new Pastry("4","Danish", 221, "2019年6月"),
new Pastry("5","Scone", 135, "2019年4月"),
new Pastry("5","Scone", 122, "2019年5月"),
new Pastry("5","Scone", 243, "2019年6月"),
new Pastry("6","test", 777, "2019年7月"),
new Pastry("6", "test", 250, "2020年4月")
};
var workbook = new XLWorkbook();
workbook.Style.Font.FontName = "游ゴシック";
var aggregateSheet = workbook.Worksheets.Add("集計");
//ヘッダ出力
aggregateSheet.Cell("A2").Value = "名前";
aggregateSheet.Cell("B2").Value = "コード";
var test = pastries.GroupBy(x => x.YearMonth);
int rowIndex = 3;
int collumnIndex = 3;
foreach (var group in test)
{
aggregateSheet.Cell(2, collumnIndex).Value = group.Key;
aggregateSheet.Cell(2, collumnIndex).Style.NumberFormat.SetFormat("yyyy年M月");
collumnIndex++;
foreach (var item in group)
{
aggregateSheet.Cell(rowIndex, "A").Value = item.Name;
aggregateSheet.Cell(rowIndex, "B").Value = item.Code;
aggregateSheet.Cell(rowIndex, collumnIndex).Value = item.NumberOfOrders;
rowIndex++;
}
}