Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

@gui-chat-plugin/spreadsheet

npm version scoria

A spreadsheet plugin for MulmoChat - a multi-modal voice chat application with OpenAI's GPT-4 Realtime API.

What this plugin does

This plugin provides a full-featured spreadsheet component with:

  • Excel-like cell editing with formula support
  • Mathematical functions (SUM, AVERAGE, MIN, MAX, etc.)
  • Text functions (CONCATENATE, LEFT, RIGHT, MID, etc.)
  • Date functions (TODAY, NOW, DATE, YEAR, MONTH, DAY, etc.)
  • Logical functions (IF, AND, OR, NOT, etc.)
  • Lookup functions (VLOOKUP, HLOOKUP, INDEX, MATCH)
  • Financial functions (PMT, PV, FV, NPV, IRR)
  • Multi-sheet support
  • Excel file export (.xlsx)
  • Saving to the host's artifacts area, with cell edits written back
  • UI in 8 languages, following the host's locale
  • Cell formatting and styling

Important: SheetJS Dependency

Note: This package uses SheetJS for Excel file export. SheetJS is not installed from npm, but directly from the official SheetJS CDN:

https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz

See SheetJS Installation Guide for details.

Installation

yarn add @gui-chat-plugin/spreadsheet gui-chat-protocol

gui-chat-protocol is a peer dependency — install it alongside the plugin; the host application provides the runtime and this plugin only declares the compatible range.

The package runs on an ES2023 runtime: Node 22 or later, Chrome 110, Safari 16, Firefox 115 or later. It uses ES2023's array methods (toSorted, toReversed) as they are, with no polyfill.

Usage

Vue Implementation (for MulmoChat)

// In src/tools/index.ts
import SpreadsheetPlugin from "@gui-chat-plugin/spreadsheet/vue";

const pluginList = [
  // ... other plugins
  SpreadsheetPlugin,
];

// In src/main.ts
import "@gui-chat-plugin/spreadsheet/style.css";

Core Only (Framework-agnostic)

import { pluginCore, TOOL_NAME } from "@gui-chat-plugin/spreadsheet";

Saving workbooks (host integration)

The plugin works in two modes, chosen by what the host passes to execute:

  • With files.artifacts (the gui-chat-protocol runtime capability): the workbook is written to artifacts/spreadsheets/YYYY/MM/<id>.json and data.sheets holds that path. The View reads and saves it through useRuntime().dispatch, so cell edits land in the same file and the model can read them back from it.
  • Without it: data.sheets holds the workbook itself, and edits are reported through updateResult only.

The View sends two dispatch calls:

kind other args result
loadSpreadsheet path { data: { sheets, version } }
saveSpreadsheet path, sheets, baseVersion? { data: { sheets: path, version } }, or { data: { sheets, version, conflict: true } }

path must be a .json file under artifacts/spreadsheets/.

version is the SHA-256 of the file's text. The View saves with the baseVersion of the sheets it shows, and the save is written only while the file still has that version. When an agent or another View wrote the file in between, nothing is written: the answer carries the file's current sheets and version with conflict: true, and the View asks the user to keep that version or save their edit over it. A save without baseVersion is written unconditionally, as before. Saves of one file through the plugin are serialized, so two Views cannot both pass the check; a write that bypasses the plugin can still land between a save's check and its write, because files.artifacts has no compare-and-write.

A host that routes the View's dispatch to the plugin's own execute (as MulmoTerminal does) needs nothing more: pluginCore.execute tells the two calls apart by kind. A host with its own dispatch route can call executeSpreadsheetDispatch(files.artifacts, args) after checking isSpreadsheetDispatchArgs(args).

The View must be rendered inside the host's PLUGIN_RUNTIME_KEY provider to load or save a saved workbook; it also takes the UI language from that runtime (en, ja, de, es, fr, ko, pt-BR, zh, falling back to English).

Upgrading from 2.x

3.0.0 changes what a host receives, so it is a major release:

  • SpreadsheetToolData.sheets is SpreadsheetSheet[] | string. With files.artifacts the tool returns the saved file's path instead of the workbook, so code that reads data.sheets as an array has to handle the path (or load it with the loadSpreadsheet dispatch).
  • pluginCore.execute also accepts SpreadsheetDispatchArgs.
  • The gui-chat-protocol peer is ^2.3.0, and the package no longer bundles it: the host's copy is used.
  • Cells may hold a boolean v, and stored workbooks may contain bare values, null gaps and {} cells (StorableCell).

Package Exports

Export Description
@gui-chat-plugin/spreadsheet Core (framework-agnostic)
@gui-chat-plugin/spreadsheet/vue Vue implementation with UI components
@gui-chat-plugin/spreadsheet/style.css Tailwind CSS styles

A host whose own guidance lists the functions a formula may call can check that list against the engine: registeredFunctionsByCategory() (from ./core) returns each category's function names, sorted, as below, and isRegisteredFunction(name) tells whether a name is one of them, in any case.

Supported Functions

Mathematical

ABS, ACOS, ACOSH, ACOT, ACOTH, AGGREGATE, ARABIC, ASIN, ASINH, ATAN, ATAN2, ATANH, BASE, CEILING, CEILING.MATH, CEILING.PRECISE, COMBIN, COMBINA, COS, COSH, COT, COTH, CSC, CSCH, DECIMAL, DEGREES, EVEN, EXP, FACT, FACTDOUBLE, FLOOR, FLOOR.MATH, FLOOR.PRECISE, GCD, INT, ISO.CEILING, LCM, LN, LOG, LOG10, MDETERM, MINVERSE, MMULT, MOD, MROUND, MULTINOMIAL, MUNIT, ODD, PERMUT, PI, POWER, PRODUCT, QUOTIENT, RADIANS, RAND, RANDARRAY, RANDBETWEEN, ROMAN, ROUND, ROUNDDOWN, ROUNDUP, SEC, SECH, SEQUENCE, SERIESSUM, SIGN, SIN, SINH, SQRT, SQRTPI, SUBTOTAL, SUMPRODUCT, SUMSQ, SUMX2MY2, SUMX2PY2, SUMXMY2, TAN, TANH, TRUNC

Angles are in radians (=SIN(RADIANS(30))). ATAN2(x, y) takes x first, as in Excel. ROUND, ROUNDUP, ROUNDDOWN, FLOOR, CEILING, POWER, SQRT, MOD, INT, TRUNC, EXP, LN, LOG and LOG10 read an argument as Excel does: an error is the answer, text that is a number is that number ("12.5", "50%"), TRUE and FALSE are 1 and 0, a blank cell or an empty argument is 0, and any other text is #VALUE! (=ROUND("a",1)). REPLACE reads its start and count the same way. An argument that is a flag (NORM.DIST's cumulative, TEXTJOIN's ignore_empty, UNIQUE's by_col and exactly_once, SORT's by_col, TOCOL's and TOROW's scan_by_column, DAYS360's method, FIXED's no_commas, LINEST's, LOGEST's, TREND's and GROWTH's const and stats) reads as IF reads its condition: a number is TRUE unless 0, TRUE and FALSE written as text are as written, a blank is FALSE, and other text is #VALUE!.

SUBTOTAL runs function 1 AVERAGE, 2 COUNT, 3 COUNTA, 4 MAX, 5 MIN, 6 PRODUCT, 7 STDEV, 8 STDEVP, 9 SUM, 10 VAR or 11 VARP over its references and leaves out the cells that hold another SUBTOTAL, so a grand total over a table with subtotals counts each value once. 101–111 are the same functions; Excel uses them to leave hidden rows out, and no row is hidden here.

AGGREGATE runs one of nineteen functions: 1–13 over references as SUBTOTAL's (7 STDEV.S, 10 VAR.S, 12 MEDIAN, 13 MODE.SNGL among them), 14–19 over an array with k (LARGE, SMALL, PERCENTILE.INC, QUARTILE.INC, PERCENTILE.EXC, QUARTILE.EXC). Its options leave out nested SUBTOTAL and AGGREGATE cells (0–3) and error values (2, 3, 6, 7): =AGGREGATE(9,6,B2:B10) sums a column past its #N/As.

An aggregate such as SUM, COUNT, AVERAGE, MAX, MIN, PRODUCT, MEDIAN, the STDEV and VAR families, NPV, the values of SUMIF, SUMIFS, AVERAGEIF, AVERAGEIFS, MAXIFS and MINIFS, and the pairs of CORREL, SLOPE, SUMX2MY2 and the like skips text inside a reference or an array, numeric text included, as Excel does: =SUM({"100",100}) is 100, and a cell whose formula answers ="5" is not counted. Text written directly as an argument is read as its number (=SUM("100",1) is 101), except by NPV, which leaves out every value written directly that is not a number, as Microsoft documents; and a number typed into a cell is a number, whether it was written as 100 or "1,200". The A-variants (COUNTA, AVERAGEA, MAXA and the like) read text as Excel does. An IF, IFS, CHOOSE or SWITCH that one value decides is read as the argument it chooses, written in its place, and an IFERROR or IFNA as its value or its fallback: =SUM(CHOOSE(2,B1:B3,TRUE)) is 1, as =SUM(TRUE) is; AND, OR and XOR read them the same way. A LET is read as its calculation with its names written in: =SUM(LET(x,TRUE,x)) is 1.

Text

ARRAYTOTEXT, ASC, BAHTTEXT, CHAR, CLEAN, CODE, CONCAT, CONCATENATE, DBCS, DOLLAR, ENCODEURL, EXACT, FIND, FINDB, FIXED, JIS, LEFT, LEFTB, LEN, LENB, LOWER, MID, MIDB, NUMBERVALUE, PHONETIC, PROPER, REGEXEXTRACT, REGEXREPLACE, REGEXTEST, REPLACE, REPLACEB, REPT, RIGHT, RIGHTB, SEARCH, SEARCHB, SUBSTITUTE, TEXT, TEXTAFTER, TEXTBEFORE, TEXTJOIN, TEXTSPLIT, TRIM, UNICHAR, UNICODE, UPPER, VALUE, VALUETOTEXT

The B functions count bytes as Excel does with a double-byte language (Japanese) as the default: a character Shift_JIS writes in two bytes, or one in a CJK block (kana, kanji, Hangul, full-width forms), is two bytes; any other counts as LEN counts it, so without such characters each answers as the function without B (=LENB("熊本") is 4, =LENB("Aeñ") is 3). FINDB and SEARCHB take a start in bytes and answer a byte position. A count that cuts a double-byte character in half keeps a space for that half (=LEFTB("熊本",3) is 熊 ). ASC turns full-width ASCII, the ideographic space and katakana into half-width (ガ becomes ガ); DBCS and JIS turn them back. PHONETIC answers a cell's own text, as Excel does for a cell with no reading kept.

CHAR and CODE number characters by Windows-1252, as Excel for Windows does (=CHAR(128) is €); UNICHAR and UNICODE by Unicode.

VALUETOTEXT writes a value as text: a number as General writes it, TRUE or FALSE, an error as its code, and text as it is, or with format 1 in quotes, a quote inside written twice (=VALUETOTEXT("a""b",1) is "a""b"). ARRAYTOTEXT writes a range or array the same way: every element joined by a comma and a space, or with format 1 as an array constant ({1,"x";TRUE,2}), a blank cell as empty text. A format other than 0 or 1 is #VALUE!. ENCODEURL percent-encodes the UTF-8 bytes of every character but the letters A to Z and a to z, the digits, -, _, . and ~.

CONCAT joins every cell of a range or table it is given, a blank one as nothing, as TEXTJOIN with no delimiter does: =CONCAT(A1:A3,"x"). CONCATENATE takes one value in each argument and answers element by element over a range.

SEARCH ignores case and reads ? as any one character, * as any run, and ~ before either as the character itself (=SEARCH("a*c","xxabbc") is 3); FIND compares literally and with case. For both, a start_num below 1 or past the end of the text is #VALUE!.

REGEXTEST, REGEXEXTRACT and REGEXREPLACE take a regular expression. Excel reads PCRE2 patterns; these run on JavaScript's regular expressions, which share the common syntax (classes, quantifiers, groups, \d, \b, lookahead and lookbehind). As in PCRE2, a leading (?i) ignores case, (?P<name>…) names a group, \A, \z and \Z anchor to the start and end, \x{41} is a character by its code, a backslash before any symbol (\-, \") is that symbol, and a ] written first in a class ([]a], [^]]) is the character. What JavaScript does not have (possessive quantifiers, atomic groups, other inline flags) is #VALUE!, as an invalid pattern or an unknown escape such as \q is. case_sensitivity is 0 (match case, the default) or 1. REGEXEXTRACT answers the first match (return_mode 0), every match as a column (1), or the first match's groups as a row (2); no match is #N/A. Given a range of texts, each answers one value, so modes 1 and 2 give each text's first match or group, as TEXTSPLIT over a range gives each text's first piece in Excel. REGEXREPLACE replaces every match (occurrence 0), the nth, or the nth from the end (-n), and reads $1, ${name}, $0 and $$ in the replacement. A pattern that could backtrack without end is #VALUE! before it runs, since nothing can stop a regular expression once it starts and the page would freeze: one where a repeated part can be split between its repeats in more than one way, because a piece of varying length in it can take what comes after that piece (^(a+)+$, (\w+\s?)*, (.*,){5}) or two of its alternatives start with the same character ((a|ab)+). A separator the piece cannot take settles it, so (\d+\.)+\d+ and ([A-Z][a-z]+)+ run, and a refused pattern can usually be written that way: ^\w+(\s\w+)*$ for ^(\w+\s?)+$, or with a short repeat written out, ^\d{1,2}[-/]?\d{1,2}[-/]?\d{2,4}$ for ^(\d{1,2}[-/]?){2}\d{2,4}$. Outside a repeat, more than three such pieces (a?a?a?a? against many a's) are refused as well. The check is cautious: it refuses some patterns that would have finished on every text.

VALUE reads a number in brackets as negative, the way the accounting format writes it: =VALUE("(1,234.50)") is -1234.5. One already signed inside, (-5), is #VALUE!. VALUE reads numeric text as a cell does: commas only between groups of three digits, one $ at the start (a sign before or after it), a % at the end, so =VALUE("1,2,3") and =VALUE("1$234") are #VALUE!.

TEXT reads a format code's ; sections (positive;negative;zero;text), quoted and \-escaped text, _x as one space, the fill *x as x written once (TEXT's answer has no column to fill, so Excel's accounting format _($* #,##0.00_) writes $ 1,234.50; a cell's display writes it the same way), [$€-407] as its symbol, the word General, and the @ of the text section, which writes the text itself (=TEXT("abc","""Name: ""@") is Name: abc). A colour ([Red], [Color10]) writes nothing, since TEXT's answer carries no colour. A condition ([>=1000]) chooses the section instead of the sign: the first of the first two sections whose condition holds, else the section without one or the third, so =TEXT(1500,"[>=1000]#,##0,""K"";0") is 2K. A negative number under conditions is written as the plain number, because Excel's documentation does not say whether such a section shows its minus sign. So =TEXT(-1234.5,"#,##0.00_);(#,##0.00)") is (1,234.50), and =TEXT(43832,"yyyy-mm-dd;@") is 2020-01-02. Text without a text section comes back unchanged.

Within a number section, 0 writes a digit or 0, # a digit or nothing, and ? a digit or a space, filled from the right across any text between them (=TEXT(5551234567,"(000) 000-0000") is (555) 123-4567). A comma between placeholders groups thousands; one after the last placeholder divides by a thousand (=TEXT(1234567,"0.0,,""M""") is 1.2M). Each % multiplies by 100, and E+ or E- writes exponent form (0.00E+00, or ##0.0E+0 for an exponent that is a multiple of three). A slash between placeholders writes a fraction, the closest one whose denominator has no more digits than its placeholders (=TEXT(1.25,"# ?/?") is 1 1/4), or the numerator rounded to a written denominator (?/4); without integer placeholders it is improper (5/4). A cell's display reads fraction codes the same way. Numbers round half away from zero at Excel's 15 significant digits.

Text in a formula is written in double quotes, a quote inside it as two (="say ""hi""" is say "hi"); a backslash is an ordinary character (="C:\"&A1).

Date & Time

DATE, DATEDIF, DATEVALUE, DAY, DAYS, DAYS360, EDATE, EOMONTH, HOUR, ISOWEEKNUM, MINUTE, MONTH, NETWORKDAYS, NETWORKDAYS.INTL, NOW, SECOND, TIME, TIMEVALUE, TODAY, WEEKDAY, WEEKNUM, WORKDAY, WORKDAY.INTL, YEAR, YEARFRAC

A formula without a format code shows its number as a date only when the number is a date by origin: the formula starts with DATE, TODAY, EDATE, EOMONTH, WORKDAY or WORKDAY.INTL, or its first reference is a date (a cell with a date format, typed as a date, or itself such a formula, on any sheet). A total that lands on 52,345 stays a number. Give a formula a format code to choose its display yourself.

A date format code is read as Excel reads it, for a cell's display and for TEXT alike: letters in any case (yyyy-mm-dd or YYYY-MM-DD), and m or mm as minutes when the part before it is an hour or the part after it a second (h:mm, h"時"mm"分"), the month otherwise. [h], [mm] and [ss] are elapsed time, the whole time in that unit: 1.5 days under [h]:mm is 36:00. A fraction of a second follows a second part with one to three 0s (h:mm:ss.000, [ss].00); the time is rounded once to the digits shown, so 59.999 seconds under mm:ss.00 is 01:00.00. A cell holding a number no date can show (below 0, or past 9999-12-31) shows ##### under a date or time code, as in Excel; TEXT answers #VALUE!.

A cell's display format with sections, a colour, _x, [$…] or quoted text is read as TEXT reads it (see Text), so Excel's own codes show as Excel shows them: #,##0.00_);[Red](#,##0.00) shows -1234.5 as (1,234.50), and yyyy-mm-dd;@ shows a date without the ;@. A colour sets no colour yet; it only no longer shows as text. A plain one-section code keeps the display's own defaults (0% shows 0.5 as 50.00%).

Dates are serial numbers on the real calendar, as in LibreOffice and Google Sheets. Excel counts a 1900-02-29 that never existed, so a serial before 61 (1900-03-01) is one day earlier here than in Excel; from 61 on they are the same.

DATE and TIME read their parts as Excel does: each part is truncated to a whole number, a year from 0 through 1899 has 1900 added (=DATE(100,1,1) is 2000-01-01), and a year below 0 or from 10000 on, or a date that rolls over past 9999-12-31 or before serial 0, is #NUM!; a TIME part above 32767, or a time adding up to less than 0, is #NUM!.

YEAR, MONTH, DAY, HOUR, MINUTE and SECOND read a serial's time rounded to the second, so =HOUR(0.9999999) is 0 (the next midnight), and a serial no date has (below 0, or past 9999-12-31) is #NUM!.

DATEVALUE and TIMEVALUE take text, as in Excel: a date through 9999-12-31 with its month as a number or a name, the year left out meaning the current one (5-JUL), or any text a cell reads as a date (a time after it left out); a time as h:mm, h:mm:ss or h AM/h PM (a date before it left out); a number, such as a cell already holding a date, is #VALUE!.

Every other date and time function reads a date written as text as that date, and a time written as text, alone or after a date, as that serial: =HOUR("7/18/2011 7:45") is 7, =MINUTE("12:45:00 PM") is 45, and a cell holding the text 12:45 reads as a quarter to one.

NETWORKDAYS.INTL and WORKDAY.INTL take the weekend as a number (1 or left out Saturday and Sunday, 2 Sunday and Monday … 7 Friday and Saturday, 11 Sunday alone … 17 Saturday alone) or as seven 0s and 1s from Monday, 1 for a day off ("0000011"); another number is #NUM! and a malformed string #VALUE!. With every day off ("1111111") NETWORKDAYS.INTL counts 0 and WORKDAY.INTL is #VALUE!. WORKDAY and WORKDAY.INTL are #NUM! for a holiday outside Excel's dates, as Microsoft documents.

DAYS360 counts every month as 30 days, by the US method (a start on a month's last day is the 30th; an end on the 31st is the 30th only after a start on the 30th) or, with TRUE, the European one (a 31st is the 30th). YEARFRAC's basis is 0 US 30/360 (left out), 1 actual/actual, 2 actual/360, 3 actual/365 or 4 European 30/360; another basis is #NUM!, and the dates may come in either order.

Logical

AND, BYCOL, BYROW, FALSE, IF, IFERROR, IFNA, IFS, ISOMITTED, LAMBDA, LET, MAKEARRAY, MAP, NOT, OR, REDUCE, SCAN, SWITCH, TRUE, XOR

A value IF, NOT, AND, OR or XOR is given directly is read as a logical value: a number is TRUE unless 0, and text reads only when it is TRUE or FALSE (in any case), a number, or empty; other text is #VALUE! (=IF("hello",1,2)). AND, OR and XOR skip the text and blanks of a reference, a single cell as much as a range, and are #VALUE! when nothing is left to read.

Lookup & Reference

ADDRESS, AREAS, CHOOSE, CHOOSECOLS, CHOOSEROWS, COLUMN, COLUMNS, DROP, EXPAND, FILTER, GROUPBY, HLOOKUP, HSTACK, INDEX, INDIRECT, LOOKUP, MATCH, OFFSET, PIVOTBY, QUERY, ROW, ROWS, SORT, SORTBY, TAKE, TOCOL, TOROW, TRANSPOSE, UNIQUE, VLOOKUP, VSTACK, WRAPCOLS, WRAPROWS, XLOOKUP, XMATCH

OFFSET and INDIRECT answer a reference, which every function reads as it reads one written out: =SUM(OFFSET(A1,1,0,3,1)) sums A2:A4, =ROW(INDIRECT("B3")) is 3, and =OFFSET(A1,0,0,2,2) alone spills. INDIRECT reads A1 text, R1C1 text (=INDIRECT("R2C3",FALSE), relative parts counted from the formula's cell) and other sheets, whole columns and rows included (=SUM(INDIRECT("A:A")), =SUM(INDIRECT("C2",FALSE)) for column B), each read as the same reference written out. AREAS counts the areas of a reference: 1 for a cell or range, and the pieces of a union written in brackets (=AREAS((A1:B2,C3)) is 2). A union is read area by area by the functions that read every argument as a list of values (SUM, COUNT, COUNTA, AVERAGE, MAX, MIN, PRODUCT, MEDIAN, the STDEV, VAR, MODE and SKEW families, GCD, LCM, AND, OR, XOR and the like, and NPV and SUBTOTAL after their first argument): =SUM((A1:A2,B1)) adds all three cells. INDEX's fourth argument, area_num, picks an area of a union (=INDEX((A1:A3,B1:B3),1,1,2) is B1; #REF! past the last area), and =AREAS(INDEX(…)) is 1. A union LET, IF, IFS, CHOOSE or SWITCH answers (or a LAMBDA a LET names, called with one) is read the same way (=SUM(IF(A9>0,(A1,B1),C1))). Anywhere else a union has no value, as in Excel: =(A1,B1) and =SUMPRODUCT((A1,B1)) are #VALUE!, and =ROWS((A1,B1)) is #REF!.

A range is written A1:C10, Data!A1:C10 or 'My Sheet'!A1:C10. A whole column (A:A, B:D) or a whole row (1:1) covers its sheet as far as the data reaches, which gives the same answers, since everything past the data is blank. ROW() and COLUMN() give the number of the cell the formula is in. Given a range of several rows, ROW answers each row number, a column that spills (=ROW(A2:A4) is {2;3;4}, =SUMPRODUCT(ROW(A1:A3)) is 6), and COLUMN of several columns each column number, in a row.

Information

CELL, ERROR.TYPE, FORMULATEXT, INFO, ISBLANK, ISERR, ISERROR, ISEVEN, ISFORMULA, ISLOGICAL, ISNA, ISNONTEXT, ISNUMBER, ISODD, ISREF, ISTEXT, N, NA, SHEET, SHEETS, T, TYPE

CELL answers what this workbook holds about a cell: "address" ($B$2, with the sheet's name when it is another sheet), "col", "row", "contents", "type" (b, l or v), "prefix", "filename" (always empty text) and the number-format types "format" (F2, ",0", C2-, P0, D1 as Microsoft lists the codes), "color" and "parentheses". Left out, the reference is the formula's own cell. "width" and "protect" are #N/A, as are INFO's "directory", "origin", "osversion", "release" and "system"; INFO answers "numfile" (the number of sheets) and "recalc" (Automatic).

An argument written empty at the end of a call is read as Excel reads it where that is settled: =VLOOKUP(A1,B:C,2,), =HLOOKUP(…,) and =MATCH(A1,B:B,) match exactly, =ROUND(1.5,) rounds to 0 digits, the month of =DB(…,) and the factor of =DDB(…,) are 0, and IF, IFERROR, IFNA, IFS, CHOOSE and SWITCH answer 0 for an empty argument they answer with (=IF(FALSE,1,)). IF's value_if_false may be left out: =IF(A1>10,"High") answers FALSE when A1 is 10 or less. Any other function reads a call ending in an empty argument as the call without it.

A blank cell is neither a number nor text, though a formula reads it as 0: =ISNUMBER(A1) and =ISTEXT(A1) are FALSE for a blank A1, =ISBLANK(A1) TRUE. The IS functions, TYPE and ERROR.TYPE answer about an error rather than with it: =ISERROR(1/0) is TRUE.

FORMULATEXT, ISFORMULA, ISREF, SHEET and SHEETS read a reference without calculating its cells, so =FORMULATEXT(A1) in A1 is no loop. FORMULATEXT gives the formula the upper-left cell holds, as written, and #N/A for a cell with none or a formula longer than 8192 characters; it and ISFORMULA are #VALUE! for an argument that is no reference, or a union. ISREF is TRUE for any reference, an OFFSET or INDIRECT call's included. SHEET numbers sheets in workbook order: this one with no argument, a reference's, or one named by text (#N/A for no such sheet); SHEETS counts the workbook's sheets, or the sheets a reference spans. A reference to a sheet that does not exist is #REF!.

An error can be written in a formula as it is shown, in any case: =IF(A1="",#N/A,A1), =IFERROR(#N/A,0). Written among the operands, it is the answer (=#DIV/0!+1 is #DIV/0!); in double quotes it is text.

Engineering

BESSELI, BESSELJ, BESSELK, BESSELY, BIN2DEC, BIN2HEX, BIN2OCT, BITAND, BITLSHIFT, BITOR, BITRSHIFT, BITXOR, CONVERT, DEC2BIN, DEC2HEX, DEC2OCT, DELTA, ERF, ERF.PRECISE, ERFC, ERFC.PRECISE, GESTEP, HEX2BIN, HEX2DEC, HEX2OCT, OCT2BIN, OCT2DEC, OCT2HEX

The base conversions follow Excel's fixed widths: 10 characters of binary (10 bits), octal (30 bits) or hexadecimal (40 bits), a negative number in two's complement.

The Bessel functions take an integer order (a fraction is truncated) and answer to the last few digits, for a large x and a large order too; Excel's own values differ from the exact ones in the eighth digit or so.

Complex numbers: COMPLEX, IMABS, IMAGINARY, IMARGUMENT, IMCONJUGATE, IMCOS, IMCOSH, IMCOT, IMCSC, IMCSCH, IMDIV, IMEXP, IMLN, IMLOG10, IMLOG2, IMPOWER, IMPRODUCT, IMREAL, IMSEC, IMSECH, IMSIN, IMSINH, IMSQRT, IMSUB, IMSUM, IMTAN

A complex number is text, as in Excel: "3+4i", "3-4j", "4i", "i", "-2.5". Each part is written as General writes a number, and the answer keeps the inputs' suffix (i or j; mixing them is #VALUE!). IMSUM and IMPRODUCT take ranges and arrays.

Database

DAVERAGE, DCOUNT, DCOUNTA, DGET, DMAX, DMIN, DPRODUCT, DSTDEV, DSTDEVP, DSUM, DVAR, DVARP

Each is D…(database, field, criteria). The field is a label or a 1-based column number. The criteria range's first row holds labels, and each row below is one alternative: a record matches when it meets every cell of any row, and a blank row matches every record. Under a label, a number or logical value matches equal values, text that begins with <, > or = compares as in SUMIFS (=Apple matches exactly), and other text matches values that begin with it. A formula under a blank label, or a label that names no field, is a computed criteria: it is written against the first record and calculated for each record, its relative rows moved down (=C2>AVERAGE($C$2:$C$9)). DGET is #VALUE! when nothing matches and #NUM! when several records do.

Statistical

ANOVA.TEST, AUTOCORREL, AVEDEV, AVERAGE, AVERAGEA, AVERAGEIF, AVERAGEIFS, BETA.DIST, BETA.INV, BETADIST, BETAINV, BINOM.DIST, BINOM.DIST.RANGE, BINOM.INV, BINOMDIST, CHIDIST, CHIINV, CHISQ.DIST, CHISQ.DIST.RT, CHISQ.INV, CHISQ.INV.RT, CHISQ.TEST, CHITEST, CONFIDENCE, CONFIDENCE.NORM, CONFIDENCE.T, CORREL, COUNT, COUNTA, COUNTBLANK, COUNTIF, COUNTIFS, COVAR, COVARIANCE.P, COVARIANCE.S, CRITBINOM, DECOMPOSE, DEVSQ, DIFF, EMA, EXPON.DIST, EXPONDIST, F.DIST, F.DIST.RT, F.INV, F.INV.RT, F.TEST, FDIST, FINV, FISHER, FISHERINV, FORECAST, FORECAST.ETS, FORECAST.ETS.CONFINT, FORECAST.ETS.SEASONALITY, FORECAST.LINEAR, FREQUENCY, FTEST, GAMMA, GAMMA.DIST, GAMMA.INV, GAMMADIST, GAMMAINV, GAMMALN, GAMMALN.PRECISE, GAUSS, GEOMEAN, GROWTH, HARMEAN, HYPGEOM.DIST, HYPGEOMDIST, INTERCEPT, KENDALL, KS.TEST, KURT, LARGE, LINEST, LOGEST, LOGINV, LOGNORM.DIST, LOGNORM.INV, LOGNORMDIST, MANNWHITNEY.TEST, MAX, MAXA, MAXIFS, MEDIAN, MIN, MINA, MINIFS, MODE, MODE.MULT, MODE.SNGL, NEGBINOM.DIST, NEGBINOMDIST, NORM.DIST, NORM.INV, NORM.S.DIST, NORM.S.INV, NORMDIST, NORMINV, NORMSDIST, NORMSINV, OUTLIERS, PCTCHANGE, PEARSON, PERCENTILE, PERCENTILE.EXC, PERCENTILE.INC, PERCENTRANK, PERCENTRANK.EXC, PERCENTRANK.INC, PERMUTATIONA, PHI, POISSON, POISSON.DIST, PROB, QUARTILE, QUARTILE.EXC, QUARTILE.INC, RANK, RANK.AVG, RANK.EQ, ROLLING, RSQ, SHAPIRO.TEST, SKEW, SKEW.P, SLOPE, SMALL, SPEARMAN, STANDARDIZE, STDEV, STDEV.P, STDEV.S, STDEVA, STDEVP, STDEVPA, STEYX, SUM, SUMIF, SUMIFS, T.DIST, T.DIST.2T, T.DIST.RT, T.INV, T.INV.2T, T.TEST, TDIST, TINV, TREND, TRIMMEAN, TTEST, VAR, VAR.P, VAR.S, VARA, VARP, VARPA, WEIBULL, WEIBULL.DIST, WILCOXON.TEST, Z.TEST, ZSCORE, ZTEST

ANOVA.TEST(range1, range2, …), MANNWHITNEY.TEST(range1, range2), WILCOXON.TEST(range) or WILCOXON.TEST(range1, range2) (paired), KS.TEST(range1, range2) and SHAPIRO.TEST(range) are not Excel functions: each returns a two-sided p value, choosing an exact or a normal null distribution as scipy.stats does by default.

Financial

ACCRINT, ACCRINTM, AMORDEGRC, AMORLINC, COUPDAYBS, COUPDAYS, COUPDAYSNC, COUPNCD, COUPNUM, COUPPCD, CUMIPMT, CUMPRINC, DB, DDB, DISC, DOLLARDE, DOLLARFR, DURATION, EFFECT, FV, FVSCHEDULE, INTRATE, IPMT, IRR, ISPMT, MDURATION, MIRR, NOMINAL, NPER, NPV, ODDFPRICE, ODDFYIELD, ODDLPRICE, ODDLYIELD, PDURATION, PMT, PPMT, PRICE, PRICEDISC, PRICEMAT, PV, RATE, RECEIVED, RRI, SLN, SYD, TBILLEQ, TBILLPRICE, TBILLYIELD, VDB, XIRR, XNPV, YIELD, YIELDDISC, YIELDMAT

The bond and security functions (the COUP functions, PRICE, YIELD, DURATION, MDURATION, ACCRINT, ACCRINTM, PRICEMAT, YIELDMAT, the discount functions DISC, INTRATE, RECEIVED, PRICEDISC and YIELDDISC, and the Treasury bill functions) take dates as the date functions do and a basis as YEARFRAC does: 0 US 30/360 (left out), 1 actual/actual, 2 actual/360, 3 actual/365, 4 European 30/360. Coupon dates step back from maturity by 12 / frequency months, staying on a month's last day when maturity is one. A date that is no date is #VALUE!; settlement on or after maturity, a frequency other than 1, 2 or 4, or a basis outside 0–4 is #NUM!.

ODDFPRICE, ODDFYIELD, ODDLPRICE and ODDLYIELD price a bond whose first or last period is odd, on the same bases; first_coupon must lie on the coupon schedule stepped back from maturity. AMORLINC and AMORDEGRC are the French system's depreciation: the first period prorated from purchase, then the rate on cost (AMORLINC) or, with a coefficient for the asset's life, on what is left, rounded to a whole number (AMORDEGRC). They take bases 0, 1, 3 and 4.

Formulas that answer a table

A formula that is a range and nothing else, such as =A1:C5 or =Data!A1:B10, answers the whole range. Its values spill from the formula's cell to the right and down, as dynamic arrays do in Excel 365. Each cell reads as =A1 would read it, so a blank cell spills as 0.

  • Blocked spills. If a cell the result needs already holds something (a value, a formula, or part of another spilled result), the formula shows #SPILL! and nothing spills.
  • Reading spilled cells. Other formulas read spilled cells like any others: =B3, =SUM(B:B) and =COUNTA(B1:B9) all see them.
  • Formatting. A spilled cell takes its own cell's number format if it has one, and the formula cell's format otherwise.
  • Saving. Only the formula is saved. The spilled values are rebuilt on every calculation.
  • One value at a time. A function that takes one value in each argument, given a range or an array there, answers element by element and spills, as in Excel 365: =IF(A1:A3>0,"Y","N"), =ROUND(B1:B9/3,1), =LEN(C1:C9), =IFERROR(1/A1:A3,""). Inside a function that reads a table, the answer is that table: =SUM(IF(A1:A9>0,B1:B9)). Arrays of different sizes line up as they do in =A1:A3*B1:C1. The functions are IF, IFERROR, IFNA, NOT, the rounding and arithmetic functions (ABS, ROUND, ROUNDUP, ROUNDDOWN, FLOOR, CEILING, INT, TRUNC, MOD, SQRT, POWER, EXP, LN, LOG, LOG10, SIGN, EVEN, ODD), the text functions (LEN, UPPER, LOWER, PROPER, TRIM, LEFT, RIGHT, MID, TEXT, VALUE, SUBSTITUTE, REPLACE, FIND, SEARCH, REPT, EXACT, CHAR, CODE, CONCATENATE, CLEAN, UNICHAR, UNICODE, FIXED, DOLLAR, NUMBERVALUE, T), the date parts (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, WEEKDAY, DATE, TIME, EDATE, EOMONTH), the IS functions, ADDRESS, the trigonometric and hyperbolic functions (SIN, COS, TAN, their inverses and reciprocals, RADIANS, DEGREES, SQRTPI), and the distributions and counting functions: every .DIST and .INV function and its compatibility name (=NORM.S.DIST(A1:A3,TRUE), =BINOM.DIST(A1:A3,10,0.5,FALSE)), CONFIDENCE.NORM, CONFIDENCE.T, STANDARDIZE, PHI, GAUSS, FISHER, FISHERINV, GAMMA, GAMMALN, FACT, FACTDOUBLE, COMBIN, PERMUT, PERMUTATIONA and BINOM.DIST.RANGE. The tests that read a sample (T.TEST, CHISQ.TEST and the like) read their ranges whole. IFS, CHOOSE and SWITCH answer element by element over an array in an argument that decides (an IFS condition, CHOOSE's index, SWITCH's expression or a case value, never its default): =CHOOSE({1,2},B1:B9,A1:A9) puts column B before column A, so =VLOOKUP(x,CHOOSE({1,2},B1:B9,A1:A9),2,FALSE) looks to the left. With one value deciding, they answer the chosen argument whole, a range included (=CHOOSE(2,A1,B1:B3) spills B1:B3), and leave the others unevaluated.

A function can answer a table too: XLOOKUP (a whole row or column; see below), INDEX (a whole row or column for a position of 0: =SUM(INDEX(A2:D9,0,3))), GROUPBY, PIVOTBY, QUERY, DECOMPOSE, EMA, DIFF, PCTCHANGE, ROLLING, ZSCORE, OUTLIERS, RANDARRAY, FILTER, SORT, SORTBY, UNIQUE, SEQUENCE, TRANSPOSE, CHOOSECOLS, CHOOSEROWS, HSTACK, VSTACK, TAKE, DROP, MMULT, MINVERSE, MUNIT, FREQUENCY, LINEST, LOGEST, TREND and GROWTH do, and they take each other's tables (=SORT(UNIQUE(A2:A100))). An answer with no cells is #CALC!. A range argument accepts such a call, as in =SUM(…) over it.

LINEST and LOGEST fit one or more x variables by least squares (LOGEST fits ln y, so every y must be above 0). With known_y a column, each column of known_x is a variable; with known_y a row, each row is; known_x of known_y's own shape is one variable. They answer the coefficients from the last x to the first, then the constant; with stats TRUE, four more rows follow: the standard errors, r² and the standard error of y, F and the degrees of freedom, and the regression and residual sums of squares, with #N/A where a row has no more values. An x collinear with the ones before it (the constant first) is left out, with a coefficient and standard error of 0 and one more degree of freedom, as Excel documents. A statistic that divides by 0 (no degrees of freedom, a perfect fit's F) is #NUM!. TREND and GROWTH answer the fitted line or curve at each new x, at known_x when new_x is left out. A polynomial is a fit over powers of x: =LINEST(B2:B20, A2:A20^{1,2,3}) fits a cubic, and =TREND(B2:B20, A2:A20^{1,2,3}, 8^{1,2,3}) answers it at 8.

Grouping

GROUPBY(row_fields, values, function, [field_headers], [total_depth], [sort_order], [filter_array]) answers a row per group of row_fields (text keys compared without regard to case), each value column aggregated by function: a function's name such as SUM, AVERAGE or COUNT, or a LAMBDA of one parameter, given the group's values as a column. PIVOTBY(row_fields, col_fields, values, function, [field_headers], [row_total_depth], [row_sort_order], [col_total_depth], [col_sort_order], [filter_array]) lays the col_fields keys across the top and the row_fields keys down the side; a cell no row has both keys for is blank.

  • field_headers: 0 none, 1 there and hidden, 2 not there and made up (Row Field 1, Value 1), 3 there and shown; left out, there when the first value is text and the second a number, and then shown. PIVOTBY reads headers the same way but shows none, in any mode.
  • Totals: a Total row (and for PIVOTBY a Total column) by default; 0 for none, negative to put it first. GROUPBY's total_depth n also gives subtotals for the first 1 … n − 1 key columns (as many as there are), each after its rows; it defaults to the number of key columns. PIVOTBY's depths are 0, 1 or -1; subtotals there are #VALUE!.
  • sort_order: columns of the answer, 1-based, negative for descending, one or an array; left out, each key column ascending. PIVOTBY's row_sort_order and col_sort_order number the key columns and then the values, which sorts by each row's or column's total.
  • filter_array: TRUE (or a number other than 0) for each data row to keep.
  • Not supported: GROUPBY's field_relationship, PIVOTBY's relative_to, more than one PIVOTBY values column and PIVOTBY subtotals; each is #VALUE!.

XLOOKUP over a table

An approximate match (MATCH with 1 or -1, VLOOKUP and HLOOKUP with TRUE or left out) looks only at values of the lookup value's kind — numbers, text or logicals — and passes over the others and errors, as Excel does: =MATCH(9.99E+307,A:A) finds the last number in a column that also holds text.

When XLOOKUP's return range has several rows and several columns, the answer is the whole matching row (the lookup ran down a column) or the whole matching column (it ran along a row), and it spills: =XLOOKUP("b", A2:A9, B2:D9) gives the three cells of B, C and D on the row where A holds "b". A return range of one row or one column gives one cell, as before. The return range has as many rows as a column lookup range, or as many columns as a row one, and the lookup range is one row or one column; otherwise the answer is #VALUE!, as in Excel.

QUERY, from Google Sheets

QUERY(data, query, [headers]) runs a query in Google's Query Language over a table and spills the answer, as Google Sheets' QUERY does. Excel has no such function. Example: =QUERY(A1:C100, "select A, sum(C) where B > 10 group by A order by sum(C) desc limit 5").

  • Clauses. select (columns, *, and the aggregates sum, avg, count, max, min), where, group by, pivot (one column), order by (asc, desc), limit, offset and label, in that order. Keywords are read in any case.
  • Column ids. When data is a reference, the columns are named by their sheet letters (B for the first column of B2:D9). For an array or a calculated table they are Col1, Col2… Ids are case-sensitive, and a backquoted id (`Col 1`) is read as written.
  • where. It takes = != <> < <= > >=, is null, is not null, contains, starts with, ends with, like (% and _) and matches (a regular expression over the whole text), joined with and, or, not and brackets. Literals are numbers, text in single or double quotes, true, false and date 'yyyy-mm-dd'. Text compares case and all.
  • Nulls and types. A comparison with a null side is unknown, as in SQL, and only rows where the condition is true are kept. Each column has the type most of its cells have; a blank, an error, or a cell of another type is null. Comparing across types, and sum or avg over text, fail. A text test turns a number or a logical into text first, as Google documents.
  • The answer. Groups come in key order, and nulls sort first. The header row is the label, else the column's header, else sum Header for an aggregate. For a pivot it is the pivot value, followed by the aggregate's name when there are several aggregates or a label. With several aggregates, the columns come per aggregate and then per pivot value, as Google lays them out. With no header at all, no header row is shown.
  • Header rows. headers is the number of header rows, joined with spaces. Left out (or -1), there is one header row when the first row is text above a column that is not mostly text.
  • Errors. An answer with nothing in it is #N/A. A query that cannot be read or run is #VALUE!.
  • Not supported. Arithmetic and scalar functions (B*2, year(A), upper(A)), format, options, the datetime and timeofday literals, more than one pivot column, and an aggregate in a pivot query's order by.

Arrays in expressions

An array constant is written in braces: {1,2,3} is a row, {1;2;3} a column and {1,2;3,4} two rows of two. Its elements are numbers, text in double quotes, TRUE, FALSE or an error such as #N/A; anything else (a reference, a call) is #ERROR!.

An expression with a range, an array constant or a table-answering call among its operands is calculated element by element and answers a table: =A2:A9*B2:B9, =A2:A9>5, =A2:A9&"!", =SORT(A2:A9)*2. Each element reads its cell as a reference to that one cell would, so a blank cell is 0 beside * and empty text beside &. Operands of different sizes line up as in Excel: a single row or column is repeated, and past the end of a shorter operand the element is #N/A (={1,2,3}+{1,2} is {2,4,#N/A}). An element that fails, such as a division by zero, is that error, and the other elements still answer. A range read inside a call belongs to the call: =SUM(A2:A9)*2 is one number. A range argument reads such an expression's cells: =SUM(A2:A9*B2:B9), =SUMPRODUCT((A2:A9>5)*B2:B9).

A function that takes one value does not yet calculate over an array (=ABS(A2:A9), =IF(A2:A9>5,1,0)); given a table of more than one cell, it answers #VALUE!.

Names and LAMBDA

LET gives names to values for one formula: =LET(total, SUM(A2:A9), total / COUNT(A2:A9)). A value may use the names before it, and a name bound to a range stays that range, so =LET(x, A2:A9, SUM(x * 2)) reads its cells as a reference does. Inside a formula, a LET answering a reference reads as that reference: with B1 empty, =LET(x, B1, x)&"!" is !, as =B1&"!" is, and =LET(x, A1:A3, x)&"!" spills as =A1:A3&"!" does. A LET holding RAND, NOW, TODAY or a workbook function is read by its value. A name is letters, digits, _ and ., starting with a letter or _; one that looks like a cell (A1), a logical value, or R or C is #NAME? (so MAKEARRAY's LAMBDA names its parameters row, col, not r, c).

LAMBDA(param1, …, calculation) is a calculation over named parameters. It is called where it is written (=LAMBDA(x, x * 2)(3) is 6), through a name (=LET(f, LAMBDA(x, x * 2), f(3))), or by:

  • MAP(array1, [array2, …], lambda): the LAMBDA at each element, the arrays lined up as in A1:A3+B1:B3, answering a table;
  • BYROW(array, lambda) and BYCOL(array, lambda): the LAMBDA at each row (a column of answers) or each column (a row of answers); a row given from a range is that row's range, so =BYROW(A2:C9, LAMBDA(row, MAX(row))) works as MAX(A2:C2) does;
  • REDUCE([initial], array, lambda(accumulator, value)): the LAMBDA over every element in reading order, carrying its answer forward. An initial value left out is 0.
  • SCAN([initial], array, lambda(accumulator, value)): as REDUCE, answering the accumulator after each element, in the array's shape: =SCAN(0, A2:A9, LAMBDA(total, x, total + x)) is a running total;
  • MAKEARRAY(rows, columns, lambda(row, column)): a table whose cells are the LAMBDA at each position, counted from 1. A size below 1 is #VALUE!.

In place of a LAMBDA, each of these takes a function's name, as Excel's eta-reduced LAMBDA: =BYROW(A2:C9, MAX) is =BYROW(A2:C9, LAMBDA(row, MAX(row))), and =REDUCE(0, A2:A9, SUM) adds them up. A name whose function cannot take that many arguments (=MAP(A2:A9, IF)) is #VALUE!, as it is for GROUPBY, PIVOTBY and ROLLING. A LAMBDA given the wrong number of arguments is #VALUE! where the call is written, inline or through a name, so =IFERROR(g(1,2),"z") answers "z"; one written but never called is #CALC!. Where one value is wanted (each element of MAP, SCAN and MAKEARRAY, each line of BYROW and BYCOL), an answer that is a table is #CALC!.

An argument written empty in a call (f(1,)) leaves its parameter out: ISOMITTED(b) is TRUE for it, so =LET(f, LAMBDA(a, b, IF(ISOMITTED(b), a, a + b)), f(1,)) is 1, and a left-out parameter used as a value reads as 0. A call with fewer arguments than parameters is #VALUE!.

Random numbers

RAND(), RANDBETWEEN(bottom, top) and RANDARRAY([rows], [columns], [min], [max], [whole_number]) draw from a stream seeded by where the call is: the sheet, the cell, and how many random calls that cell's formula has made before it, in the order they are evaluated. A workbook therefore calculates to the same numbers each time, and the agent and the page showing the sheet see the same table. Excel draws new numbers at every recalculation instead. RANDBETWEEN includes both bounds, rounding bottom up and top down, and is #NUM! when no whole number lies between them. RANDARRAY truncates its sizes as SEQUENCE does (0 is #CALC!, below 0 #VALUE!), and is #VALUE! when min is not below max, or when whole numbers are asked for between bounds that are not whole.

Time series

AUTOCORREL(values, lag), EMA(values, alpha), DECOMPOSE(values, period, [model]), DIFF, PCTCHANGE, ROLLING, ZSCORE and OUTLIERS are not Excel functions; they compute what statsmodels and pandas do. A series is one row or one column of numbers in order, read as TREND and LINEST read their cells (text that is a number counts). A blank, or text that is not a number, is #VALUE! rather than skipped, since skipping would shift every point after it.

  • AUTOCORREL is the autocorrelation at one lag, as statsmodels' acf computes it.
  • EMA is the exponential moving average (pandas ewm(alpha=…, adjust=False)), one value per point; alpha must be in (0, 1].
  • DIFF(values, [periods]) is each point less the one periods before it (pandas diff), and PCTCHANGE(values, [periods]) its change as a fraction (pandas pct_change), one value per point. periods is 1 when left out, negative to look ahead, and must be a whole number; a point with none at that distance is #N/A (pandas' NaN), and a change from 0 is #DIV/0!, as =0/0 is, including from 0 to 0, where pandas writes NaN. A result past the largest number is #NUM!, where pandas writes inf.
  • ROLLING(values, window, function, [min_periods]) is pandas rolling(window, min_periods).agg(function): for each point, the function over the last window points up to it, given as a column. The function is a function's name (SUM, AVERAGE, MEDIAN, STDEV, …) or a LAMBDA of one parameter, as in GROUPBY, and answers as it would for those cells (STDEV of one point is #DIV/0!). A point with fewer than min_periods points in its window (the window when left out) is #N/A. The window is a whole number from 1, and min_periods a whole number from 0 to the window.
  • ZSCORE(values) is each value's distance from the mean in sample standard deviations, pandas' (s - s.mean()) / s.std(); with fewer than two values, or all of them equal, each point is #DIV/0! (pandas' NaN), and where the mean or the spread passes the largest number, #NUM!, as for an overflow.
  • OUTLIERS(values, [method], [threshold]) is TRUE for each value outside the fences: with "iqr" (the default), more than threshold (1.5 unless given) interquartile ranges below the lower quartile or above the upper one, the quartiles as pandas' quantile and PERCENTILE.INC compute them; with "zscore", more than threshold (3 unless given) standard deviations from the mean, as ZSCORE measures them. A negative threshold is #NUM!, and so is each point when the quartiles' range or the z-scores pass the largest number.
  • DECOMPOSE is the classical decomposition (statsmodels seasonal_decompose): for each point, its trend (a centred moving average over one period, #N/A where the window does not fit), seasonal and residual parts, additive by default or "multiplicative". The lag and the period must be whole numbers (a fraction is #NUM!); the period must be at least 2, with two full periods of values.

FORECAST.ETS(target_date, values, timeline, [seasonality], [data_completion], [aggregation]), FORECAST.ETS.CONFINT(target_date, values, timeline, [confidence_level], [seasonality], [data_completion], [aggregation]) and FORECAST.ETS.SEASONALITY(values, timeline, [data_completion], [aggregation]) take Excel's arguments, but Excel does not publish how it fits its model, so their values can differ from Excel's. They fit additive Holt-Winters (a level, a trend and an additive season, as statsmodels' ExponentialSmoothing(trend="add", seasonal="add") smooths them), choosing the smoothing parameters that minimise the squared one-step errors.

  • The timeline. The timeline can be in any order. Values at one time are combined by the aggregation: 0 or 1 AVERAGE (the default), 2 COUNT, 3 COUNTA, 4 MAX, 5 MEDIAN, 6 MIN, 7 SUM. The step is the smallest gap between times, and every gap must be a whole number of steps.
  • Missing points. A missing point, a blank value included, is filled on the line between its neighbours (data_completion 1, the default; the nearest value at either end) or with 0 (data_completion 0). More than 30% of the points missing is #NUM!.
  • Seasonality. 1 (the default) detects the season's length, 0 fits none, and a whole number up to 8760 gives it. The detected length is the highest peak of the autocorrelation (with the trend line removed) above 1.96/√n, between 2 and half the series. FORECAST.ETS.SEASONALITY answers it, or 0 when there is none.
  • The interval. FORECAST.ETS.CONFINT is the half-width of the interval around the forecast, at 95% unless given. Its variance grows with each step ahead as for ETS(A,A,A) (Hyndman et al.).
  • Errors.
    • #NUM!: a target before the last time, a seasonality, data_completion, aggregation or confidence outside its values, fewer than two full seasons of values (three points without a season), or a step that is not constant.
    • #N/A: values and timeline of different sizes.
    • #VALUE!: text, or a blank time.

Monthly or weekly totals need no function of their own: group by each date's month end, =GROUPBY(MAP(A2:A100, LAMBDA(d, EOMONTH(d, 0))), B2:B100, SUM) (or by each week's first day). EOMONTH takes one date, so MAP gives it each one.

Workbook functions

A workbook can define functions of its own, for an analysis no built-in function does. Each sheet may carry an optional functions list; a function defined on any sheet is callable from every sheet of that workbook:

{
  "name": "Data",
  "functions": [
    {
      "name": "MOVING.AVG",
      "params": ["values", "n"],
      "body": "const xs = values.flat().filter((v) => typeof v === 'number'); const tail = xs.slice(-n); return tail.reduce((a, b) => a + b, 0) / tail.length;"
    }
  ],
  "data": [[{ "v": 100 }, { "v": "=MOVING.AVG(A1:A30, 7)" }]]
}
  • A function body is JavaScript, run in QuickJS (WebAssembly) with no DOM, network, file system or timers, at most 50 ms per call, 2 s per calculation and 16 MB of memory. A body is at most 20,000 characters. Each function has a global scope of its own.
  • A function body has no regular expressions: compiling a pattern is work no time limit can stop. A body that holds a literal (/^a+$/) is reported as not loading, and one that builds a pattern while it runs (new RegExp(...), 'text'.match('b'), .search, .matchAll) shows #VALUE!. String methods that take plain text (split(','), replace('x', 'y'), replaceAll, indexOf, includes) still work, and a formula has REGEXTEST, REGEXEXTRACT and REGEXREPLACE.
  • A range argument arrives as rows of cells (an array of arrays, a blank cell as null); a single cell and any other argument as its value. A whole column or row (A:A, 2:2) arrives as the range it covers in its sheet's data. An argument that is an error is passed on without calling the function.
  • Return a number, text or true/false, or a table: an array of rows ([[1, 2], [3, 4]]), which spills like any table. A flat array is one column, and short rows are filled with #N/A. A time-out or a non-finite number shows #NUM!; a thrown error, an empty array or any other return value shows #VALUE!. In a table, null is a blank cell and any other value that is not a number, text or a logical is a #VALUE! cell.
  • A name is letters and digits, parts joined by dots, and cannot be a built-in function's. presentSpreadsheet says in its reply which definitions could not be used.
  • presentSpreadsheet's reply also lists formula cells that calculate to an error (a few, and how many in all), so an agent can fix a workbook before handing it over: the saved file holds formulas, not results. When some of them only take their error from another (=A1*2 beside an =A1 that is #N/A), it names the cells the errors start from instead, each with how many others take their error from it: an error is followed into the cells a formula names (cells, ranges, other sheets, whole columns and rows) while they hold the same error. A reference built while calculating (the text INDIRECT reads, the cells OFFSET lands on) is not followed.
  • A circular reference (cells that read each other round in a loop, a cell reading itself, a range holding its own cell, or a loop through INDIRECT or OFFSET or other sheets) shows #REF! in every cell of the loop, as Google Sheets does, and a cell reading one takes the error. The reply names each loop's cells.
  • presentSpreadsheet takes an optional explain, a list of cells (["Summary!B4"]; a cell without a sheet name is on the first sheet; at most five). The reply explains each one, which Excel only does by hand with Trace Precedents and Evaluate Formula:
    • its value and its formula;
    • each cell and range the formula names, with its value. Text is in quotes, so a stray space shows. A cell holding a formula shows that formula too, and a range shows its size, how many cells of each kind it holds, its first error and its first values (a range past ten thousand cells says that only the first ten thousand were looked at);
    • what the formula's parts come to: the calls at its top (=SUM(B:B)/COUNT(B:B)), or a lone call's arguments that are calculations (=IFERROR(VLOOKUP(…),0) shows the VLOOKUP). Each part is evaluated alone, in the cell's own place, so ROW() and whole columns read as they do there. Nothing inside a LET or LAMBDA is evaluated, since its names mean nothing outside it.
  • presentSpreadsheet also takes dependents, a list of cells (at most five). For each one, the reply names the formula cells that read it, directly or through other formula cells, each with its value and formula and the cell it is reached through: what a change to that cell would move. Excel shows this only by hand, one level of arrows at a time with Trace Dependents. A formula is found through the cells and ranges it names, whole columns and rows and other sheets included. References built while calculating (INDIRECT, OFFSET) are not followed, and a formula that reads only a table's spilled cells, not the cell the table spills from, is not found. The list stops after a thousand cells and says so.
  • presentSpreadsheet also takes goalSeek: up to three requests { "cell": "Model!C1", "value": 100, "changing": "Inputs!B1" }. Each one asks which value of the changing cell makes the formula cell equal the value, as Excel's Goal Seek does. The changing cell must hold a number or be blank. The reply gives the value found, or says plainly that none was found, with the closest value tried and the reason: a limit of calculations or time, a formula that jumps across the value, one that does not change with the cell, or one that is no number. The search starts from the cell's current value. It tries secant steps, then narrows any bracket around the value by regula falsi, and looks farther out and closer in on both sides when there is none. The workbook is not changed: the agent writes the value if it wants it.
  • Each workbook's functions get a QuickJS instance of their own, so a failure in one (an abort while freeing a runtime that ran out of time) cannot affect another.
  • QuickJS loads only for a workbook that defines functions. The View and readCalculatedRange load it themselves; a host calling calculatedRange directly passes the set from loadCustomFunctions.

Development

# Install dependencies
yarn install

# Start dev server (http://localhost:5173/)
yarn dev

# Build
yarn build

# Type check
yarn typecheck

# Lint
yarn lint

Test Prompts

Try these prompts to test the plugin:

  1. "Create a budget spreadsheet with income and expenses columns"
  2. "Make a multiplication table from 1 to 10"
  3. "Create a spreadsheet to track monthly sales with SUM totals"

License

MIT

Related

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages