Skip to main content

Formulae公式

File Format Support (click to show)

The parser will translate from the storage representation to A1-Style strings, while the writer will translate from A1-Style strings to the file format.解析器将从存储表示转换为A1样式字符串,而编写器将从A1样式字符串转换为文件格式。

FormatsParseWriteArrayDynamicStorage Representation
XLSX / XLSMA1-Style strings
XLSBBIFF parsed tokens
XLSBIFF parsed tokens
XLMLRC-style strings
SYLKA1/RC-style strings
CSV / TXTA1-Style strings
ODS / FODS / UOSOpenFormula strings
WK*Lotus parsed tokens
WQ* / WB* / QPWQuattro Pro tokens
NUMBERSNumbers parsed tokens

X (✕) marks features that are not supported by the file formats. There is no way to mark a dynamic array formula in the XLS file format.标记文件格式不支持的功能。无法以XLS文件格式标记动态数组公式。

SheetJS supports reading and writing formulae for a number of file formats. When supported, formulae will always be exported.SheetJS支持多种文件格式的读写公式。如果支持,公式将始终导出。

By default, formulae are not always imported. To ensure formula parsing, the option cellFormula: true should be passed to the parser.默认情况下,并不总是导入公式。为了确保公式解析,应该将选项cellFormula: true传递给解析器。

Typically file data will be available as an ArrayBuffer, either downloaded with fetch / XMLHttpRequest or user-submitted with a File Input element. cellFormula: true should be added to the second options argument:通常,文件数据将作为ArrayBuffer可用,可以使用fetch/XMLHttpRequest下载,也可以使用用户提交的File Input元素。cellFormula: true应添加到第二个选项参数中:

/* using read in the browser, `cellFormula` is in the second argument在浏览器中使用read,`cellFormula`在第二个参数中 */
const ab = await (await fetch("test.xlsx")).arrayBuffer();
const workbook = XLSX.read(ab, { cellFormula: true });
// ------------------------------^^^^^^^^^^^^^^^^^

A1-Style FormulaeA1样式公式

The A1-Style formula string is stored in the f field of the cell object. Spreadsheet software typically represent formulae with a leading = sign, but SheetJS formulae omit the =.A1样式公式字符串存储在单元格对象的f字段中。电子表格软件通常用前导=符号表示公式,但SheetJS公式省略了=

"A1-Style" describes A1-Style in more detail.更详细地描述了A1样式。

Live Example (click to hide)

For example, consider this test file:例如,考虑以下测试文件

Screenshot

The following code block fetches the file, parses and prints info on cell D1:以下代码块获取文件,解析并打印单元格D1上的信息:

Result
Loading...
Live Editor

Single-Cell Formulae单单元格公式

For simple formulae, the f key of the desired cell can be set to the actual formula text. This worksheet represents A1=1, A2=2, and A3=A1+A2:对于简单的公式,可以将所需单元格的f键设置为实际的公式文本。此工作表表示A1=1A2=2A3=A1+A2

var worksheet = {
"!ref": "A1:A3", // Worksheet range A1:A3
A1: { t: "n", v: 1 }, // A1 is a number (1)
A2: { t: "n", v: 2 }, // A2 is a number (2)
A3: { t: "n", v: 3, f: "A1+A2" } // A3 =A1+A2
};

Utilities like aoa_to_sheet will accept cell objects in lieu of values:aoa_to_sheet等实用程序将接受单元格对象来代替值:

var worksheet = XLSX.utils.aoa_to_sheet([
[ 1 ], // A1
[ 2 ], // A2
[ {t: "n", v: 3, f: "A1+A2"} ] // A3
]);
Live Example (click to hide)

This demo creates a worksheet where A1=1, A2=2, and A3=A1+A2.此演示创建了一个工作表,其中A1=1A2=2A3=A1+A2

Result
Loading...
Live Editor

Cells with formula entries but no value will be serialized in a way that Excel and other spreadsheet tools will recognize. 具有公式条目但没有值的单元格将以Excel和其他电子表格工具能够识别的方式进行序列化。This library will not automatically compute formula results! 此库不会自动计算公式结果!For example, the following worksheet will include the BESSELJ function but the result will not be available in JavaScript:例如,以下工作表将包括BESSELJ函数,但结果在JavaScript中不可用:

var worksheet = XLSX.utils.aoa_to_sheet([
[ 3.14159, 2 ], // Row "1"
[ { t: "n", f: "BESSELJ(A1,B1)" } ] // Row "2" will be calculated on file open将在打开文件时计算第“2”行
])

If the actual results are needed in JS, SheetJS Pro offers a formula calculator component for evaluating expressions, updating values and dependent cells, and refreshing entire workbooks.如果JS中需要实际结果,SheetJS Pro提供了一个公式计算器组件,用于计算表达式、更新值和依赖单元格以及刷新整个工作簿。

Array Formulae数组公式

Assign an array formula指定数组公式

XLSX.utils.sheet_set_array_formula(worksheet, range, formula);

Array formulae are stored in the top-left cell of the array block. 数组公式存储在数组块的左上角单元格中。All cells of an array formula have a F field corresponding to the range. 数组公式的所有单元格都有一个与该范围相对应的F字段。A single-cell formula can be distinguished from a plain formula by the presence of F field.单细胞公式可以通过F字段的存在与普通公式区分开来。

The following snippet sets cell C1 to the array formula {=SUM(A1:A3*B1:B3)}:以下代码段将单元格C1设置为数组公式{=SUM(A1:A3*B1:B3)}

// API function
XLSX.utils.sheet_set_array_formula(worksheet, "C1", "SUM(A1:A3*B1:B3)");

// ... OR raw operations
worksheet["C1"] = { t: "n", f: "SUM(A1:A3*B1:B3)", F: "C1:C1" };

For a multi-cell array formula, every cell has the same array range but only the first cell specifies the formula. 对于多单元格数组公式,每个单元格都具有相同的数组范围,但只有第一个单元格指定该公式。Consider D1:D3=A1:A3*B1:B3:考虑D1:D3=A1:A3*B1:B3

// API function
XLSX.utils.sheet_set_array_formula(worksheet, "D1:D3", "A1:A3*B1:B3");

// ... OR raw operations
worksheet["D1"] = { t: "n", F: "D1:D3", f: "A1:A3*B1:B3" };
worksheet["D2"] = { t: "n", F: "D1:D3" };
worksheet["D3"] = { t: "n", F: "D1:D3" };

Utilities and writers are expected to check for the presence of a F field and ignore any possible formula element f in cells other than the starting cell. 实用程序和编写器应检查F字段的存在,并忽略起始单元格以外的单元格中任何可能的公式元素fThey are not expected to perform validation of the formulae!它们不应进行公式验证!

Live Example (click to show)
Result
Loading...
Live Editor

Dynamic Array Formulae动态数组公式

Assign a dynamic array formula指定动态数组公式

XLSX.utils.sheet_set_array_formula(worksheet, range, formula, true);

Released in 2020, Dynamic Array Formulae are supported in the XLSX/XLSM and XLSB file formats. They are represented like normal array formulae but have special cell metadata indicating that the formula should be allowed to adjust the range.动态数组公式于2020年发布,支持XLSX/XLSM和XLSB文件格式。它们像普通数组公式一样表示,但具有特殊的单元格元数据,指示应允许公式调整范围。

An array formula can be marked as dynamic by setting the cell D property to true. 通过将单元格D属性设置为true,可以将数组公式标记为动态公式。 The F range is expected but can be the set to the current cell:F范围是预期的,但可以设置为当前单元格:

// API function
XLSX.utils.sheet_set_array_formula(worksheet, "C1", "_xlfn.UNIQUE(A1:A3)", 1);

// ... OR raw operations
worksheet["C1"] = { t: "s", f: "_xlfn.UNIQUE(A1:A3)", F:"C1", D: 1 }; // dynamic
Live Example (click to show)
Result
Loading...
Live Editor

Localization本地化

SheetJS operates at the file level. Excel stores formula expressions using the English (United States) function names. For non-English users, Excel uses a localized set of function names.SheetJS在文件级别运行。Excel使用英文(美国)函数名存储公式表达式。对于非英语用户,Excel使用一组本地化的函数名。

For example, when the computer language and region is set to Spanish, Excel interprets =CONTAR(A1:C3) as if CONTAR is the COUNT function. 例如,当计算机语言和区域设置为西班牙语时,Excel将=CONTAR(A1:C3)解释为CONTARCOUNT函数。However, in the actual file, Excel stores COUNT(A1:C3).但是,在实际文件中,Excel存储COUNT(A1:C3)

Function arguments are separated with commas. For example, the Spanish Excel formula =CONTAR(A1:C3;B4:D6) is equivalent to the SheetJS formula string COUNT(A1:A3,B4:D6)函数参数用逗号分隔。例如,西班牙语Excel公式=CONTAR(A1:C3;B4:D6)等效于SheetJS公式字符串COUNT(A1:A3,B4:D6)

JSON Translation table.

Function Name Translator函数名称转换器 (click to hide)
Result
Loading...
Live Editor

Prefixed "Future Functions"前缀为“未来函数”

Functions introduced in newer versions of Excel are prefixed with _xlfn. when stored in files. When writing formula expressions using these functions, the prefix is required for maximal compatibility:在较新版本的Excel中引入的函数以_xlfn.为前缀。当存储在文件中时。使用这些函数编写公式表达式时,需要前缀以实现最大兼容性:

// Broadest compatibility
XLSX.utils.sheet_set_array_formula(worksheet, "C1", "_xlfn.UNIQUE(A1:A3)", 1);

// Can cause errors in spreadsheet software
XLSX.utils.sheet_set_array_formula(worksheet, "C1", "UNIQUE(A1:A3)", 1);

When reading a file, the xlfn option preserves the prefixes.读取文件时,xlfn选项会保留前缀。

Functions requiring `_xlfn.` prefix (click to show)

This list is growing with each Excel release.此列表随着每个Excel版本的发布而不断增加。

ACOT
ACOTH
AGGREGATE
ARABIC
BASE
BETA.DIST
BETA.INV
BINOM.DIST
BINOM.DIST.RANGE
BINOM.INV
BITAND
BITLSHIFT
BITOR
BITRSHIFT
BITXOR
BYCOL
BYROW
CEILING.MATH
CEILING.PRECISE
CHISQ.DIST
CHISQ.DIST.RT
CHISQ.INV
CHISQ.INV.RT
CHISQ.TEST
COMBINA
CONCAT
CONFIDENCE.NORM
CONFIDENCE.T
COT
COTH
COVARIANCE.P
COVARIANCE.S
CSC
CSCH
DAYS
DECIMAL
ECMA.CEILING
ERF.PRECISE
ERFC.PRECISE
EXPON.DIST
F.DIST
F.DIST.RT
F.INV
F.INV.RT
F.TEST
FIELDVALUE
FILTERXML
FLOOR.MATH
FLOOR.PRECISE
FORECAST.ETS
FORECAST.ETS.CONFINT
FORECAST.ETS.SEASONALITY
FORECAST.ETS.STAT
FORECAST.LINEAR
FORMULATEXT
GAMMA
GAMMA.DIST
GAMMA.INV
GAMMALN.PRECISE
GAUSS
HYPGEOM.DIST
IFNA
IFS
IMCOSH
IMCOT
IMCSC
IMCSCH
IMSEC
IMSECH
IMSINH
IMTAN
ISFORMULA
ISO.CEILING
ISOMITTED
ISOWEEKNUM
LAMBDA
LET
LOGNORM.DIST
LOGNORM.INV
MAKEARRAY
MAP
MAXIFS
MINIFS
MODE.MULT
MODE.SNGL
MUNIT
NEGBINOM.DIST
NETWORKDAYS.INTL
NORM.DIST
NORM.INV
NORM.S.DIST
NORM.S.INV
NUMBERVALUE
PDURATION
PERCENTILE.EXC
PERCENTILE.INC
PERCENTRANK.EXC
PERCENTRANK.INC
PERMUTATIONA
PHI
POISSON.DIST
QUARTILE.EXC
QUARTILE.INC
QUERYSTRING
RANDARRAY
RANK.AVG
RANK.EQ
REDUCE
RRI
SCAN
SEC
SECH
SEQUENCE
SHEET
SHEETS
SKEW.P
SORTBY
STDEV.P
STDEV.S
SWITCH
T.DIST
T.DIST.2T
T.DIST.RT
T.INV
T.INV.2T
T.TEST
TEXTJOIN
UNICHAR
UNICODE
UNIQUE
VAR.P
VAR.S
WEBSERVICE
WEIBULL.DIST
WORKDAY.INTL
XLOOKUP
XOR
Z.TEST

Caveats注意事项

In some cases, seemingly valid formulae may be rejected by spreadsheet software.在某些情况下,看似有效的公式可能会被电子表格软件拒绝。

EVALUATE is a supported function in WPS Office. It is not valid in a cell formula in Excel. It can be used in an Excel defined name when exporting to XLSM format but not XLSX. 是WPS Office中支持的功能。它在Excel的单元格公式中无效。当导出为XLSM格式而不是XLSX格式时,它可以在Excel定义的名称中使用。This is a limitation of Excel. Since WPS Office accepts files with EVALUATE, the writer does not warn or throw errors.这是Excel的一个限制。由于WPS Office接受带有EVALUATE的文件,因此编写器不会发出警告或引发错误。