Live Razor Page Samples

DataTable to Excel Workbook with Formats and Formulas

This sample shows how to insert data from a DataTable into an Excel workbook, merging the data with formatting and formulas. The results are displayed in custom Tag Helper.

Supporting Files

The following files are utilized by this sample:

namespace Website.Pages.Support.Samples.RazorPages.TagHelpers
    public partial class DataTableToTemplateWorkbookModel : PageModel
        public SpreadsheetGear.IRange Range { get; set; }

        public void OnGet()
            // Create a DataSet from an XML file and retrieve an order table.
            System.Data.DataSet dataset = new System.Data.DataSet();
            System.Data.DataTable datatable = dataset.Tables["OrderItems"];

            // Open the template workbook, which contains number formats and formulas, and get an IRange from a defined name
            SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook("files/spiceordertemplate.xlsx");
            SpreadsheetGear.IRange range = workbook.Names["SetDataRange"].RefersToRange;

            // Insert the DataTable into the template worksheet range. The InsertCells
            // flag will cause the formatted range to be adjusted for the inserted data.
            range.CopyFromDataTable(datatable, SpreadsheetGear.Data.SetDataFlags.InsertCells);

            // Set range (from a defined name) to be displayed by the Tag Helper.
            Range = workbook.Names["GetDataRange"].RefersToRange;
@model DataTableToTemplateWorkbookModel

<range-to-table range="@Model.Range" has-header-row="true"></range-to-table>
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace Website.Pages.Support.Samples.RazorPages
    /// <summary>
    /// Simple Tag Helper to convert a range of cells into an HTML table.
    /// </summary>
    public class RangeToTableTagHelper : TagHelper
        /// <summary>
        /// The Range to be converted to an HTML table.
        /// </summary>
        public SpreadsheetGear.IRange Range { get; set; }

        /// <summary>
        /// Specifies whether to treat the first row in Range as a header row
        /// </summary>
        public bool HasHeaderRow { get; set; } = true;

        public override void Process(TagHelperContext context, TagHelperOutput output)
            // Don't generate anything if there isn't a range.
            if (Range == null)
                output.TagName = "div";
                output.Content.SetHtmlContent(@"<div class='alert alert-info'><i>No range data was provided.</i></div>");

            // Set output tag to <table> and add some styling courtesy of Bootstrap.
            output.TagName = "table";
            output.Attributes.Add("class", "table table-striped table-bordered table-hover table-sm");
            // Store table in a StringBuilder as we construct it for faster processing of string concatenation.
            StringBuilder sb = new StringBuilder();

            // If HasHeaderRow we'll treat the first row as a header row and remaining rows as normal rows in the 
            // dataRange.
            SpreadsheetGear.IRange dataRange = Range;
            if (HasHeaderRow)
                // Get reference to first row.
                SpreadsheetGear.IRange headerRow = dataRange[0, 0, 0, dataRange.ColumnCount - 1];
                sb.Append("<thead class='table-dark'><tr>");

                // Loop over and render each cell in the "headerRow" range.
                foreach (SpreadsheetGear.IRange cell in headerRow)
                    // Get some basic formatting from this cell.
                    string classes = GetClassAttribute(cell);

                    // Using IRange.Text here, which will return the formatted value of a cell.
                    sb.Append("<th" + (classes.Length > 0 ? $" class='{classes}'" : "") + ">").Append(cell.Text).Append("</th>");

                // Since the top row is a header row, we should remove it from dataRange, for which the
                // IRange.Subtract(...) method is a perfect tool to do so.
                dataRange = dataRange.Subtract(headerRow);

            // Calling dataRange.Rows returns the same range as dataRange, but in a form that allows
            // it to be looped over in row "chunks", such as A1:C1, A2:C2, A3:C3 in the range A1:C3.
            foreach (SpreadsheetGear.IRange row in dataRange.Rows)
                // Similarly calling IRange.Columns will allow each column in the provided range to be
                // iterated over (in this case each column of one row will consist of just a single cell).
                foreach (SpreadsheetGear.IRange cell in row.Columns)
                    // Get some basic formatting from this cell.
                    string classes = GetClassAttribute(cell);

                    // Again, using IRange.Text here, which will return the formatted value of a cell.
                    sb.Append("<td" + (classes.Length > 0 ? $" class='{classes}'" : "") + ">").Append(cell.Text).Append("</td>");

            // Set output of tag helper to the HTML table.

        /// <summary>
        /// A very basic routine to add formatting to HTML output based on the corresponding IRange cell's formatting.
        /// </summary>
        /// <param name="cell">A single cell, for which formatting classes will be based off.</param>
        /// <returns>A string such as ' class="..."' if formatting options are found, otherwise an empty string.</returns>
        private static string GetClassAttribute(SpreadsheetGear.IRange cell)
            List<string> classes = new List<string>();
            // Horizontal Alignment
            if (cell.HorizontalAlignment == SpreadsheetGear.HAlign.Center)
            else if (cell.HorizontalAlignment == SpreadsheetGear.HAlign.Right)

            // Basic font formatting
            if (cell.Font.Bold)
            if (cell.Font.Italic)
            if (cell.Font.Underline != SpreadsheetGear.UnderlineStyle.None)

            // If desired, this could be expanded to include other formatting, such as other font settings, cell 
            // interior color, etc.

            if (classes.Count > 0)
                return string.Join(' ', classes);
            return "";