Click here to Skip to main content
15,886,422 members
Articles / Web Development / HTML

Implementing Excel export in ASP.NET5 using Open XML

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
19 Sep 2015MIT1 min read 9.3K   1  
Today in ASP.NET forums I found one question about implementing Exel export from ASP.NET5 / MVC 6. So I thought I will implement and share the code. So this post is about implementing excel export using Open XML SDK in ASP.NET 5.

Today in ASP.NET forums I found one question about implementing Exel export from ASP.NET5 / MVC 6. So I thought I will implement and share the code. So this post is about implementing excel export using Open XML SDK in ASP.NET 5.

The question is about Excel export using Office Interop, as it is not a recommended approach and I am not sure, can we use COM / Interop in ASP.NET 5, I am using Open XML SDK.

First include the Open XML SDK in the project.json file.

"dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-beta6",
    "Microsoft.AspNet.Mvc": "6.0.0-beta6",
    "Microsoft.AspNet.Server.IIS": "1.0.0-beta6",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta6",
    "Microsoft.Framework.Logging.Console": "1.0.0-beta6",
    "DocumentFormat.OpenXml":"2.5.0"
},
"frameworks": {
     "dnx451": {
         "frameworkAssemblies": {
             "WindowsBase":"4.0.0"
         }
    }
}

Open XML SDK requires WindowsBase reference, so I removed the DNX Core framework reference and included WindowsBase as framework assembly. Now you need write the code for exporting excel from the model. The excel generation code I took from an SO post. In that code, the export was using Data Table, I modified the code to support model object.

And finally to download the file, you can use the FileContentResult type, to return byte array.

For some enterprise application, you may need to include Excel export option for all the Grids, for such purposes, you can create a ActionResult class, which accepts the model and exports the file.

public class ExcelFileResult : FileResult
{
    public ExcelFileResult(object model) :
        base(new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
    {
    }
    
    protected override Task WriteFileAsync(HttpResponse response, CancellationToken cancellation)
    {
        
    }
}

Happy Programming :) The complete source code is available on GitHub

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Technical Lead
India India
Working as Tech. Lead

My blog : dotnetthoughts.net.
You can follow me in twitter : @anuraj

Comments and Discussions

 
-- There are no messages in this forum --