Create and Save an Excel file with ASP.NET Core

Gembox.Spreadsheet supports the .NET Standard. As a result of this, various platforms are supported such as .NET Framework, .NET Core, Xamarin, and Universal Windows Platform (UWP).

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

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

Save data to file in ASP.NET Core MVC Screenshot
@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>
        <hr />
        <button type="submit" class="btn btn-default">Export</button>
    </form>
</body>
</html>
using GemBox.Spreadsheet;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;

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;
            default:
                throw new NotSupportedException("Format '" + format + "' is not supported.");
        }
    }

    private static byte[] GetBytes(ExcelFile file, SaveOptions options)
    {
        using (MemoryStream 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(SpreadsheetLicense.Value);

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

        SaveOptions options = GetSaveOptions(model.SelectedFormat);
        ExcelFile book = new ExcelFile();
        ExcelWorksheet sheet = book.Worksheets.Add("Sheet1");

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

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

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

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

        return File(GetBytes(book, 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; }
}

Check next example or download examples from GitHub.