Skip to content

Instantly share code, notes, and snippets.

@gon250
Last active June 4, 2018 15:23
Show Gist options
  • Save gon250/c9057b4ecfccc3d41662 to your computer and use it in GitHub Desktop.
Save gon250/c9057b4ecfccc3d41662 to your computer and use it in GitHub Desktop.
EPPLUS - c#
[Authorize]
public ActionResult Export() {
try
{
var fileDownloadName = "FileName-" + DateTime.Now.ToShortDateString() + ".xlsx";
const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var clients = this._clientsRepository.Get();
var package = new ExcelPackage();
var ws = UtilsCsv.CreateSheet(package, "Client Details", 1);
//Header
ws.Cells[1, 1].Value = "Id";
ws.Cells[1, 2].Value = "Website";
ws.Cells[1, 3].Value = "Name";
ws.Cells[1, 4].Value = "Email";
ws.Cells[1, 5].Value = "Company";
ws.Cells[1, 6].Value = "File Name";
ws.Cells[1, 7].Value = "Newsletter";
ws.Cells[1, 1].Style.Font.Bold = true;
ws.Cells[1, 2].Style.Font.Bold = true;
ws.Cells[1, 3].Style.Font.Bold = true;
ws.Cells[1, 4].Style.Font.Bold = true;
ws.Cells[1, 5].Style.Font.Bold = true;
ws.Cells[1, 6].Style.Font.Bold = true;
ws.Cells[1, 7].Style.Font.Bold = true;
//Body
var n = 2;
var site = this._siteRepository.Get();
foreach (var client in clients) {
ws.Cells[n, 1].Value = client.id;
ws.Cells[n, 2].Value = site.Where(s => s.id == client.siteId).Select(s => s.name).FirstOrDefault();
ws.Cells[n, 3].Value = client.name;
ws.Cells[n, 4].Value = client.email;
ws.Cells[n, 5].Value = client.company;
ws.Cells[n, 6].Value = client.fileName;
ws.Cells[n, 7].Value = client.allowNews;
}
var fileStream = new MemoryStream();
package.SaveAs(fileStream);
fileStream.Position = 0;
var fsr = new FileStreamResult(fileStream, contentType) { FileDownloadName = fileDownloadName };
return fsr;
}
catch (Exception) {
return RedirectToAction("Index", "Clients", new { errors = true });
}
}
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Create Excel Worksheet: here is the function which creates a worksheet
/// </summary>
/// <param name="p"></param>
/// <param name="sheetName"></param>
/// <param name="sheetId"></param>
/// <returns></returns>
public static ExcelWorksheet CreateSheet(ExcelPackage p, string sheetName, int sheetId)
{
p.Workbook.Worksheets.Add(sheetName);
ExcelWorksheet ws = p.Workbook.Worksheets[sheetId];
ws.Name = sheetName; //Setting Sheet's name
ws.Cells.Style.Font.Size = 11; //Default font size for whole sheet
ws.Cells.Style.Font.Name = "Calibri"; //Default Font name for whole sheet
return ws;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment