C# create excel using EPPlus

Date: 2019-10-24

https://www.nuget.org/packages/EPPlus/

// using OfficeOpenXml;
// using OfficeOpenXml.Style;

using (var excel = new ExcelPackage())
{
	var ws = excel.Workbook.Worksheets.Add("My worksheet");
	ws.DefaultColWidth = 22;
	ws.Column(2).Width = 25.29;
	ws.Cells.AutoFitColumns(15, 100); // Auto fit columns with minimum and maximum

	var range = ws.Cells[1, 1, 1, 8]; // first row 8 columns
	range.Style.Font.Bold = true;
	range.AutoFilter = true;

	range.Style.Fill.PatternType = ExcelFillStyle.Solid; // must be set to apply background color
	range.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(242, 242, 242));
	range.Style.Font.Color.SetColor(Color.White);	
	range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center
	range.Style.Numberformat.Format = "#,##0.00";

	ws.View.ShowGridLines = false; // hide excel grid
	ws.PrinterSettings.Orientation = eOrientation.Landscape;
	ws.PrinterSettings.PrintArea = ws.Cells[1, 1, 100, 8];
	ws.PrinterSettings.FitToPage = true;

	try
	{
		// Embed file by using: Properties > Build Action > Embedded Resource
		using (Stream imageStream = GetType().Assembly.GetManifestResourceStream("NameSpace.FileName.png")) 
		{
			var image = Image.FromStream(imageStream);
			var picture = ws.Drawings.AddPicture("Picture", image);
			picture.SetPosition(100, 100);
		}
	}
	catch (Exception ex)
	{
		Log.Write(LogLevel.Error, "Failed to add image to Excel", ex);
	}
	var fileName = "c:\temp\temp.xlsx";
	using (var stream = File.Open(fileName, FileMode.Create))
	{
		excel.SaveAs(stream);
	}
}

Update 2020-03-03 Using a Pivot Table:

/*
using OfficeOpenXml;
using OfficeOpenXml.Drawing.Chart;
using OfficeOpenXml.Style;
using OfficeOpenXml.Table.PivotTable;
*/

public class BusinessUnitActivityResourceFlatData
{
	public DateTime Date { get; set; }
	public string Week { get; set; }
	public string Month { get; set; }
	public int? BusinessUnitId { get; set; }
	public string BusinessUnitName { get; set; }
	public int? ActivityId { get; set; }
	public string ActivityDescription { get; set; }
	public int? ResourceId { get; set; }
	public string ResourceDescription { get; set; }
	public double Hours { get; set; }
}

public byte[] ExportBusinessUnitActivityResourcePivotTable(string title, IEnumerable<BusinessUnitActivityResourceFlatData> data, BusinessUnitActivityResourceGrouping grouping)
{
	using (var ep = new ExcelPackage())
	{
		var showDate = false;
		var showWeek = true;
		var showActivity = false;

		if (grouping == BusinessUnitActivityResourceGrouping.Day_BusinessUnit_Activity_Resource || 
			grouping == BusinessUnitActivityResourceGrouping.Day_BusinessUnit_Resource)
		{
			showDate = true;
		}

		if (grouping == BusinessUnitActivityResourceGrouping.Day_BusinessUnit_Activity_Resource ||
			grouping == BusinessUnitActivityResourceGrouping.Week_BusinessUnit_Activity_Resource ||
			grouping == BusinessUnitActivityResourceGrouping.Month_BusinessUnit_Activity_Resource)
		{
			showActivity = true;
		}

		if (grouping == BusinessUnitActivityResourceGrouping.Month_BusinessUnit_Activity_Resource ||
			grouping == BusinessUnitActivityResourceGrouping.Month_BusinessUnit_Resource)
		{
			showWeek = false;
		}

		var wsPivot = ep.Workbook.Worksheets.Add("Draaitabel");
		var wsData = ep.Workbook.Worksheets.Add("Gegevens");

		wsPivot.Cells[1, 1].Value = title;
		wsPivot.Cells[1, 1].Style.Font.Bold = true;

		wsPivot.DefaultColWidth = 20;
		wsData.DefaultColWidth = 20;
		wsData.View.FreezePanes(2, 1);

		var y = 1;
		var x = 1;

		if (showDate)
		{ 
			wsData.Cells[y, x++].Value = "Datum";
		}
		if (showWeek)
		{ 
			wsData.Cells[y, x++].Value = "Week";
		}
		wsData.Cells[y, x++].Value = "Maand";
		wsData.Cells[y, x++].Value = "KostenplaatsId";
		wsData.Cells[y, x++].Value = "Kostenplaats";
		if (showActivity)
		{ 
			wsData.Cells[y, x++].Value = "ActiviteitId";
			wsData.Cells[y, x++].Value = "Activiteit";
		}
		wsData.Cells[y, x++].Value = "MiddelId";
		wsData.Cells[y, x++].Value = "Middel";
		wsData.Cells[y, x++].Value = "Uren";

		y = 2;
		foreach (var row in data)
		{
			x = 1;
			if (showDate)
			{ 
				wsData.Cells[y, x++].Value = row.Date.ToString("yyyy-MM-dd");
			}
			if (showWeek)
			{ 
				wsData.Cells[y, x++].Value = row.Week;
			}
			wsData.Cells[y, x++].Value = row.Month;
			wsData.Cells[y, x++].Value = row.BusinessUnitId;
			wsData.Cells[y, x++].Value = row.BusinessUnitName;
			if (showActivity)
			{ 
			wsData.Cells[y, x++].Value = row.ActivityId;
			wsData.Cells[y, x++].Value = row.ActivityDescription;
			}
			wsData.Cells[y, x++].Value = row.ResourceId;
			wsData.Cells[y, x++].Value = row.ResourceDescription;
			wsData.Cells[y, x++].Value = row.Hours;
			y++;
		}

		var colCount = x - 1;
		for (int i = 1; i < colCount; i++)
		{
			wsData.Column(i).AutoFit(10, 40);
		}

		// enable autofilter
		wsData.Cells[1, 1, 1, colCount].Style.Font.Bold = true;
		wsData.Cells[1, 1, y, colCount].AutoFilter = true;

		var pivotTable = wsPivot.PivotTables.Add(wsPivot.Cells["A2"], wsData.Cells[1, 1, y, colCount], "Draaitabel");

		pivotTable.ShowHeaders = true;
		pivotTable.UseAutoFormatting = true;
		pivotTable.ApplyWidthHeightFormats = true;
		pivotTable.ShowDrill = true;
		pivotTable.FirstHeaderRow = 1;
		pivotTable.FirstDataRow = 2;
		pivotTable.FirstDataCol = 1;
		pivotTable.DataOnRows = false;

		var groupByRows = new List<string> { "Middel" };
		var groupByColumns = new List<string> { "Kostenplaats" };
		var summaryColumns = new List<string> { "Uren" };

		foreach (string row in groupByRows)
		{
			var field = pivotTable.Fields[row];
			pivotTable.RowFields.Add(field);
			field.Sort = eSortType.Ascending;
		}

		foreach (string row in groupByColumns)
		{
			var field = pivotTable.Fields[row];
			pivotTable.ColumnFields.Add(field);
			field.Sort = eSortType.Ascending;
		}

		foreach (string column in summaryColumns)
		{
			var field = pivotTable.Fields[column];
			var dataField = pivotTable.DataFields.Add(field);
			dataField.Function = DataFieldFunctions.Sum;
		}

		var chart = wsPivot.Drawings.AddChart("Draaitabel grafiek", eChartType.Line, pivotTable);
		chart.SetPosition(36, 0, 1, 0);
		chart.SetSize(1000, 600);

		return ep.GetAsByteArray();
	}
}
27150cookie-checkC# create excel using EPPlus