Live Razor Page Samples

Formula Evaluation

This sample demonstrates evaluating a single Excel compatible formula entered into a web form.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Threading.Tasks;

namespace Website.Pages.Support.Samples.RazorPages.Calculations
{
    public partial class FormulaEvaluationModel : PageModel
    {
        [BindProperty]
        public string Formula { get; set; }

        public string Result { get; set; }

        public void OnGet()
        {
            Formula = @"TEXT(STDEV(1, 2, 3, 4), ""0.00"")";
        }


        public void OnPost()
        {

            // Create a new empty workbook and get the first sheet. 
            SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();
            SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets[0];

            // Evaluate the input formula.
            object result = worksheet.EvaluateValue(Formula ?? "");

            // Display the result to the user.
            if (result == null)
                Result = "Empty cell or invalid formula.";
            else if (result is SpreadsheetGear.ValueError valueError)
                Result = $"Value Error: #{valueError.ToString().ToUpper()}!";
            else
                Result = $"Result calculated from EvaluateValue(...) method: {result}";

        }
    }
}
@page
@model FormulaEvaluationModel

<div class="row mt-4">
  <div class="col-12 offset-0 col-md-10 offset-md-1">
    <div class="card">
      <h4 class="card-header">Enter an Excel-compatible formula to evaluate:</h4>
      <div class="card-body">
        <!-- Input Form -->
        <form asp-page="FormulaEvaluation" method="post">
          <div class="mb-2">
            <label asp-for="Formula" class="form-label"></label>
            <div class="input-group">
              <span class="input-group-text"><i class="fal fa-equals"></i></span>
              <input asp-for="Formula" class="form-control" />
            </div>
            <div class="form-text ms-5">Don't include a leading equals sign in the formula.</div>
          </div>
          <div class="text-end">
            <button class="btn btn-primary"><i class="fa-fw fas fa-play-circle"></i> Evaluate</button>
          </div>
        </form>

        <!-- Output Result Here -->
        @if (Model.Result != null)
        {
          <div class="m-4">
            <div class="alert alert-info">
              @Model.Result
            </div>
          </div>
        }
      </div>
    </div>
  </div>
</div>