Create and save an Excel file in ASP.NET Core

GemBox.Spreadsheet provides a support for .NET Standard which is why it can be used on various .NET platforms such as .NET Framework, .NET Core, Xamarin and Universal Windows Platform (UWP).

This allows us to create different kinds of applications using, for example, ASP.NET, Windows Forms, or WPF, and to run them on different operating systems, including Windows, Linux, and macOS.

Also, GemBox.Spreadsheet provides direct support for newer versions of .NET Core (.NET Core 3.0 and higher).

The following example is a simple ASP.NET Core MVC application that exports data to an Excel file in the specified output format.

An ASP.NET Core MVC application that exports data with GemBox.Spreadsheet
Screenshot of an ASP.NET Core MVC application that exports data with GemBox.Spreadsheet
A file exported from an ASP.NET Core MVC application with GemBox.Spreadsheet
Screenshot of a file exported from an ASP.NET Core MVC application with GemBox.Spreadsheet
@model Spreadsheet.Samples.Core.Controllers.WorkbookModel

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width">
    <meta charset="utf-8" />
    <title>Create an Excel Workbook</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <style type="text/css">
        thead tr {
            text-align: center;
        }

        .table th {
            color: white;
            background-color: rgb(242, 101, 34);
            padding: 0.5rem;
        }

        .table td {
            padding: 0.5rem;
        }

        .table input {
            font-size: 0.9rem;
            padding: 0.3rem 0.35rem;
        }

        .first-column {
            text-align: center;
        }
    </style>
</head>
<body style="padding:20px; font-size: 0.9rem">
    <form asp-action="Create">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <table class="table table-bordered table-condensed">
            <colgroup>
                <col style="width: 10%" />
                <col style="width: 45%" />
                <col style="width: 45%" />
            </colgroup>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                </tr>
            </thead>
            <tbody>
                @for (int i = 0; i < Model.Items.Count; i++)
                {
                    <tr>
                        <td><input asp-for="Items[i].Id" type="text" class="form-control-plaintext first-column" readonly /></td>
                        <td><input asp-for="Items[i].FirstName" type="text" class="form-control" /></td>
                        <td><input asp-for="Items[i].LastName" type="text" class="form-control" /></td>
                    </tr>
                }
            </tbody>
        </table>
        <div>
            <h4>Output format:</h4>
            <div class="form-check">
                <input id="XLSX" name="SelectedFormat" type="radio" class="form-check-input" checked value="XLSX" />
                <label for="XLSX" class="form-check-label">XLSX</label>
            </div>
            <div class="form-check">
                <input id="XLS" name="SelectedFormat" type="radio" class="form-check-input" value="XLS" />
                <label for="XLS" class="form-check-label">XLS</label>
            </div>
            <div class="form-check">
                <input id="ODS" name="SelectedFormat" type="radio" class="form-check-input" value="ODS" />
                <label for="ODS" class="form-check-label">ODS</label>
            </div>
            <div class="form-check">
                <input id="CSV" name="SelectedFormat" type="radio" class="form-check-input" value="CSV" />
                <label for="CSV" class="form-check-label">CSV</label>
            </div>
            <div class="form-check">
                <input id="HTML" name="SelectedFormat" type="radio" class="form-check-input" value="HTML" />
                <label for="HTML" class="form-check-label">HTML</label>
            </div>
            <div class="form-check">
                <input id="PDF" name="SelectedFormat" type="radio" class="form-check-input" value="PDF" />
                <label for="PDF" class="form-check-label">PDF</label>
            </div>
            <div class="form-check">
                <input id="XPS" name="SelectedFormat" type="radio" class="form-check-input" value="XPS" />
                <label for="XPS" class="form-check-label">XPS</label>
            </div>
            <div class="form-check">
                <input id="BMP" name="SelectedFormat" type="radio" class="form-check-input" value="BMP" />
                <label for="BMP" class="form-check-label">BMP</label>
            </div>
            <div class="form-check">
                <input id="GIF" name="SelectedFormat" type="radio" class="form-check-input" value="GIF" />
                <label for="GIF" class="form-check-label">GIF</label>
            </div>
            <div class="form-check">
                <input id="JPG" name="SelectedFormat" type="radio" class="form-check-input" value="JPG" />
                <label for="JPG" class="form-check-label">JPG</label>
            </div>
            <div class="form-check">
                <input id="PNG" name="SelectedFormat" type="radio" class="form-check-input" value="PNG" />
                <label for="PNG" class="form-check-label">PNG</label>
            </div>
            <div class="form-check">
                <input id="TIF" name="SelectedFormat" type="radio" class="form-check-input" value="TIF" />
                <label for="TIF" class="form-check-label">TIF</label>
            </div>
            <div class="form-check">
                <input id="WMP" name="SelectedFormat" type="radio" class="form-check-input" value="WMP" />
                <label for="WMP" class="form-check-label">WMP</label>
            </div>
        </div>
        <hr />
        <button type="submit" class="btn btn-default">Export</button>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.IO;
using GemBox.Spreadsheet;
using Microsoft.AspNetCore.Mvc;

public class WorkbookController : Controller
{
    private static readonly IList<WorkbookItemModel> data = new List<WorkbookItemModel>()
        {
            new WorkbookItemModel() { Id = 100, FirstName = "John", LastName = "Doe"},
            new WorkbookItemModel() { Id = 101, FirstName = "Fred", LastName = "Nurk"},
            new WorkbookItemModel() { Id = 102, FirstName = "Hans", LastName = "Meier"},
            new WorkbookItemModel() { Id = 103, FirstName = "Ivan", LastName = "Horvat"},
            new WorkbookItemModel() { Id = 104, FirstName = "Jean", LastName = "Dupont"},
            new WorkbookItemModel() { Id = 105, FirstName = "Mario", LastName = "Rossi"},
        };

    private static SaveOptions GetSaveOptions(string format)
    {
        switch (format.ToUpperInvariant())
        {
            case "XLSX":
                return SaveOptions.XlsxDefault;
            case "XLS":
                return SaveOptions.XlsDefault;
            case "ODS":
                return SaveOptions.OdsDefault;
            case "CSV":
                return SaveOptions.CsvDefault;
            case "HTML":
                return SaveOptions.HtmlDefault;
            case "PDF":
                return SaveOptions.PdfDefault;
            case "XPS":
                return SaveOptions.XpsDefault;
            case "BMP":
                return new ImageSaveOptions() { Format = ImageSaveFormat.Bmp };
            case "GIF":
                return new ImageSaveOptions() { Format = ImageSaveFormat.Gif };
            case "JPG":
                return new ImageSaveOptions() { Format = ImageSaveFormat.Jpeg };
            case "PNG":
                return new ImageSaveOptions() { Format = ImageSaveFormat.Png };
            case "TIF":
                return new ImageSaveOptions() { Format = ImageSaveFormat.Tiff };
            case "WMP":
                return new ImageSaveOptions() { Format = ImageSaveFormat.Wmp };
            default:
                throw new NotSupportedException("Format '" + format + "' is not supported.");
        }
    }

    private static byte[] GetBytes(ExcelFile file, SaveOptions options)
    {
        using (var stream = new MemoryStream())
        {
            file.Save(stream, options);
            return stream.ToArray();
        }
    }

    public IActionResult Create()
    {
        return View(new WorkbookModel() { Items = data, SelectedFormat = "XLSX" });
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(WorkbookModel model)
    {
        SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

        if (!ModelState.IsValid)
            return View(model);

        var options = GetSaveOptions(model.SelectedFormat);
        var workbook = new ExcelFile();
        var worksheet = workbook.Worksheets.Add("Sheet1");

        var style = worksheet.Rows[0].Style;
        style.Font.Weight = ExcelFont.BoldWeight;
        style.HorizontalAlignment = HorizontalAlignmentStyle.Center;
        worksheet.Columns[0].Style.HorizontalAlignment = HorizontalAlignmentStyle.Center;

        worksheet.Columns[0].SetWidth(50, LengthUnit.Pixel);
        worksheet.Columns[1].SetWidth(150, LengthUnit.Pixel);
        worksheet.Columns[2].SetWidth(150, LengthUnit.Pixel);

        worksheet.Cells["A1"].Value = "ID";
        worksheet.Cells["B1"].Value = "First Name";
        worksheet.Cells["C1"].Value = "Last Name";

        for (int r = 1; r <= model.Items.Count; r++)
        {
            var item = model.Items[r - 1];
            worksheet.Cells[r, 0].Value = item.Id;
            worksheet.Cells[r, 1].Value = item.FirstName;
            worksheet.Cells[r, 2].Value = item.LastName;
        }

        return File(GetBytes(workbook, options), options.ContentType, "Create." + model.SelectedFormat.ToLowerInvariant());
    }
}

public class WorkbookModel
{
    public string SelectedFormat { get; set; }
    public IList<WorkbookItemModel> Items { get; set; }
}

public class WorkbookItemModel
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Want more?

Next example GitHub

Check the next example or select an example from the menu. You can also download our examples from the GitHub.


Like it?

Download Buy

If you want to try the GemBox.Spreadsheet yourself, you can download the free version. It delivers the same performance and set of features as the professional version, but with some operations limited. To remove the limitation, you need to purchase a license.