Stop Reimplementing Excel Business Logic in JavaScript

The Excel Reimplementation Problem

Many developers have faced this: a complex Excel workbook has to be turned into code. Long after the first version, you are still looking for the reason why your results do not match Excel.

Why Reimplementation Fails

The Formula Translation Problem

A simple Excel formula:

=IF(B2>1000,
  VLOOKUP(A2,PriceTable,3,FALSE)*0.9,
  VLOOKUP(A2,PriceTable,2,FALSE))

becomes JavaScript that needs its own lookup:

function calculatePrice(productId, quantity) {
  // Needs an implementation of VLOOKUP:
  // 1-based columns, exact and approximate match,
  // and the same behaviour as Excel when nothing is found
  const column = quantity > 1000 ? 3 : 2;
  const basePrice = vlookup(productId, priceTable, column, false);
  return quantity > 1000 ? basePrice * 0.9 : basePrice;
}

Hidden Dependencies

That formula may depend on:

  • other sheets
  • defined names
  • lookup tables that somebody maintains
  • cells that change with a drop-down selection

Your JavaScript has to recreate the whole dependency graph, not one formula.

Excel-Specific Functions

// Excel: =WORKDAY(TODAY(), 10, Holidays)
// In JavaScript you have to build:
// - the WORKDAY logic
// - weekend definitions
// - holiday handling
// - Excel's date system

The Real Cost

  • The first version is the small part. Finding the remaining differences takes longer, because each one hides in an edge case.
  • Rounding and dates. Excel and JavaScript round and count days differently in places. The differences are small and hard to find.
  • Two versions. The business team keeps changing the workbook. Every change has to be made a second time in code, and nobody notices when one is forgotten.

The Solution: Use the Workbook Directly

Before: Reimplementation

// A growing code base that tries to match Excel
class ExcelClone {
  calculatePrice(inputs) {
    // reimplemented formulas
    // differs from the workbook in edge cases
    // has to be changed whenever the workbook changes
  }
}

After: One Call

const url =
  'https://spreadapi.io/api/v1/services/{serviceId}/execute?flatten=true';

const response = await fetch(url, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ inputs: { customer: 'ACME', quantity: 1000 } })
});

const data = await response.json();
const price = data.result.finalPrice;

The workbook calculates, your code sends inputs and reads outputs. With flatten=true the answer carries result, one object with the output names as keys. Without it you read the list outputs. See The API response.

How It Works

  1. Import your Excel workbook. The formulas stay as they are.
  2. Choose inputs and outputs. Click the cells a caller may fill and the cells that hold results.
  3. Publish and call. Every call is calculated by the workbook.

The steps are in Your first service, the overview on the page Excel to API.

Common Patterns

One Helper for All Calculations

async function calculate(serviceId, inputs) {
  const url =
    `https://spreadapi.io/api/v1/services/${serviceId}/execute?flatten=true`;
  const response = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ inputs })
  });
  const data = await response.json();
  if (!response.ok) throw new Error(data.message || data.error);
  return data.result;
}

Dynamic Pricing

app.post('/api/quote', async (req, res) => {
  try {
    res.json(await calculate(PRICING_SERVICE_ID, req.body));
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

Commission

// Before: a long function full of copied rules
// After:
async function calculateCommission(sales, tier, region) {
  const result = await calculate(COMMISSION_SERVICE_ID, {
    sales, tier, region
  });
  return result.commission;
}

An input is a single value: a number, a text or yes/no. A list of values, such as a series of cash flows, belongs into the workbook or is passed as several inputs.

Benefits

For Developers

  • The reimplemented formulas can go
  • No more searching for differences to Excel
  • Time for the application itself

For the Business Team

  • They keep working in Excel
  • A changed workbook is live after import and publish, without a code release
  • One version of the logic

Migration Guide

Step 1: Find the Reimplemented Calculations

git grep -n -E 'calculate|compute|formula'

Step 2: Publish the Workbook

  • Find the original Excel file
  • Import it into SpreadAPI
  • Choose inputs and outputs
  • Test with values whose results you know

Step 3: Replace the Code

Replace each reimplemented function with a call, as in the commission example above, and compare old and new results for a while before you delete the old code.

Common Objections

"What about performance?"

We measured our public demo quote calculator, a workbook with four sheets: a calculation took about 20 ms on the server, and the whole round trip from a client in Germany had a median of 97 ms. That holds for that workbook only. The method and all numbers are in Excel API response time.

"What if the Excel workbook has errors?"

A reimplementation would copy the same errors. With one version you fix them once, in the workbook.

"We need version control"

SpreadAPI does not keep a version history of a service. Callers get the published version until you publish again. Keep the Excel files in your own version control or document management, and export the workbook from SpreadAPI when you need the current state. See Replace the workbook with a new version.

"Our logic is in macros"

VBA macros do not run in a service, and links to other workbooks are not followed. That logic has to be rebuilt with formulas. See Supported Excel features.

Best Practices

1. Start Small

Pick one Excel model, replace its reimplementation, compare the results, and expand from there.

2. Reuse Results

const cache = new Map();

async function calculateCached(serviceId, inputs) {
  const key = serviceId + JSON.stringify(inputs);
  if (!cache.has(key)) {
    cache.set(key, await calculate(serviceId, inputs));
  }
  return cache.get(key);
}

SpreadAPI also stores the result of identical inputs for up to 15 minutes. See Caching and performance.

3. Handle Errors

A refused input answers with HTTP 400 and a text that names the input. A formula error in an output cell, such as #VALUE!, is returned as the value with status 200. Check for both.

The Bottom Line

Reimplementing Excel in JavaScript means maintaining the same logic twice. Calling the workbook as an API keeps one version: the one its owner maintains.

Try SpreadAPI

Questions? Contact support@airrange.io