Click here to Skip to main content
15,887,350 members
Articles / Web Development / ASP.NET
Tip/Trick

ASP.NET MVC5 - AngularJS, Create XLS file using ExcelPackage

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
20 Dec 2015CPOL1 min read 11K   8  
This article walks you through the steps for create a report in Excel using EPPlus (ExcelPackage)

Introduction

This article walks you through the steps for create a report in Excel using ExcelPackage.

ExcelPackage provides server-side generation of Excel 2007 spreadsheets.
It is a set of classes and wrappers around the .NET 3.0 System.IO.Packaging API and the new Office Open XML file format. It extracts away the complexity of dealing with the individual XML components making it real easy to create sophisticated spreadsheets on the server.

STEP 1 - Create ASP.NET Web Application

Check the link below, to see all the steps to create a Web Api wtih Entity Framework code first implementation.

http://social.technet.microsoft.com/wiki/contents/articles/26795.asp-net-webapi-entity-framework-code-first.aspx

 

STEP 2 - Install Nuget

Now in order to use ExcelPackage we need to install a Nuget package.

So on the Visual Studio 2015, select the follow menu option:

Tools-> Library Package manager -> Manage NuGet Packages for Solution

Search for EPPlus and select the option Install.

 

STEP 3 - Excel Generate Class

On ContactController add new method to call GenerateXLS

 

C#
C#
using System; 
using System.Collections.Generic; 
using System.Data.Entity; 
using System.Data.Entity.Infrastructure; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Web.Http; 
using SampleEF6.Models; 
using System.Threading.Tasks; 
using System.Web; 
using System.IO; 
using System.Net.Http.Headers; 
 
namespace SampleEF6.Controllers 
{ 
    public class ReportController : ApiController 
    { 
        // GET api/<controller> 
        [HttpGet] 
        public async Task<httpresponsemessage> GetXLSReport() 
        { 
            string fileName = string.Concat("Contacts.xls"); 
            string filePath = HttpContext.Current.Server.MapPath("~/Report/" + fileName); 
 
            ContactController contact = new ContactController(); 
            List<contact> contacList = contact.Get().ToList(); 
 
            await SampleEF6.Report.ReportGenerator.GenerateXLS(contacList, filePath); 
 
            HttpResponseMessage result = null; 
            result = Request.CreateResponse(HttpStatusCode.OK); 
            result.Content = new StreamContent(new FileStream(filePath, FileMode.Open)); 
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); 
            result.Content.Headers.ContentDisposition.FileName = fileName; 
 
            return result; 
        } 
    } 
}
</contact></httpresponsemessage></controller>

 Create the GenerateXLS method like this:

 

C#
C#
using OfficeOpenXml; 
using OfficeOpenXml.Style; 
using SampleEF6.Models; 
using System; 
using System.Collections.Generic; 
using System.Drawing; 
using System.IO; 
using System.Linq; 
using System.Reflection; 
using System.Threading.Tasks; 
using System.Web; 
 
namespace SampleEF6.Report 
{ 
    public class ReportGenerator 
    { 
        public static Task GenerateXLS(List<contact> datasource, string filePath) 
        { 
            return Task.Run(() => 
            { 
                using (ExcelPackage pck = new ExcelPackage()) 
                { 
                    //Create the worksheet 
                    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Contacts"); 
 
                    ws.Cells[1, 1].Value = "Id"; 
                    ws.Cells[1, 2].Value = "Name"; 
                    ws.Cells[1, 3].Value = "Address"; 
                    ws.Cells[1, 4].Value = "City"; 
                    ws.Cells[1, 5].Value = "Country"; 
 
                    for (int i = 0; i < datasource.Count(); i++) 
                    { 
                        ws.Cells[i + 2, 1].Value = datasource.ElementAt(i).Id; 
                        ws.Cells[i + 2, 2].Value = datasource.ElementAt(i).Name; 
                        ws.Cells[i + 2, 3].Value = datasource.ElementAt(i).Address; 
                        ws.Cells[i + 2, 4].Value = datasource.ElementAt(i).City; 
                        ws.Cells[i + 2, 5].Value = datasource.ElementAt(i).Country; 
                    } 
 
                    using (ExcelRange rng = ws.Cells["A1:A5"]) 
                    { 
                        rng.Style.Font.Bold = true; 
                        rng.Style.Fill.PatternType = ExcelFillStyle.Solid;        //Set Pattern for the background to Solid 
                        rng.Style.Fill.BackgroundColor.SetColor(Color.DarkGray);  //Set color to DarkGray 
                        rng.Style.Font.Color.SetColor(Color.Black); 
                    } 
 
                    pck.SaveAs(new FileInfo(filePath)); 
                } 
            }); 
        } 
    } 
}
</contact>

STEP 4 - Run Application

 

 

Resources

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Devscope
Portugal Portugal
I am João Sousa, and since i finish my degree I’m working in software development using Microsoft technologies.

I was awarded

Microsoft Most Valuable Professional (MVP) 2015 – .Net

My profissional profile:

Azure Developer
.NET Developer

My Certifications:

MCTS - .NET Framework - Application Development Foundation
MCTS - .NET Framework 2.0 - Windows-based Client Development
MCTS - .NET Framework 3.5 ADO.NET Applications
MCTS - .NET Framework 3.5 ASP.NET Applications
MCSD - Programming in HTML5 with JavaScript and CSS3
MCSD - Developing ASP.NET MVC 4 Web Applications
MCSD - Developing Windows Azure and Web Services
MCSA Office 365 - Managing Office 365 Identities and Requirements
MCSA Office 365 - Enabling Office 365 Services
MCSD - Implementing Microsoft Azure Infrastructure Solutions

Comments and Discussions

 
-- There are no messages in this forum --