公式

公式是 Univer 提供的核心能力之一,它可以讓你在儲存格中使用公式來計算數值,公式支援的函數和 Excel 一致,包括數學、邏輯、文字、日期等等。

如果工作簿中的公式數量較多,公式計算可能占用主執行緒並導致頁面卡頓。建議將公式計算放到 Worker 進程中執行,以降低對頁面渲染和互動的影響。具體配置方式請參考 Web Workers 章節。

配置

以下是公式外掛相關配置項的連結:

外掛配置項
@univerjs/engine-formulaIUniverEngineFormulaConfig
@univerjs/sheets-formulaIUniverSheetsFormulaBaseConfig

使用 initialFormulaComputing 控制活頁簿載入時的計算方式。若已儲存的公式結果過期,使用 CalculationMode.FORCED 重新計算。預設模式下,相同選項放在 formula 內。

依接入模式將以下選項合併到既有的初始化設定中,保留其他外掛、語言、主題與容器設定,請勿重複註冊同一外掛。

TypeScript
import { CalculationMode, UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula'univer.registerPlugin(UniverSheetsFormulaPlugin, {  initialFormulaComputing: CalculationMode.FORCED,})
  • CalculationMode.FORCED: 重新計算所有公式。
  • CalculationMode.WHEN_EMPTY: 預設值:只計算沒有已儲存 v 值的公式儲存格。
  • CalculationMode.NO_CALCULATION: 初始化時不計算公式。

跨活頁簿引用

跨活頁簿公式可在 Report 中彙總 Sales.xlsx 的資料。與同一活頁簿內的跨工作表引用不同,它還需指定來源活頁簿。

引用語法

情境範例意義
同一活頁簿的其他工作表=SUM(Data!A1:A10)目前活頁簿的 Data 工作表
其他活頁簿的儲存格範圍=SUM('[Sales.xlsx]Data'!A1:A10)Sales.xlsx 的 Data 工作表
其他活頁簿的表格=SUM(Sales.xlsx!SalesTable[Amount])已存在的 SalesTable 表格的 Amount 欄

Sales.xlsx 是活頁簿名稱,不是檔案路徑或下載網址。寫入公式不會讀取磁碟、下載 Excel 或連接另一個瀏覽器頁面。結構化引用需要先建立對應的表格。

引用同一實例中已載入的活頁簿

基礎公式引擎要求兩份活頁簿位於同一 Univer 實例與計算環境。以下程式碼在 Sheets 初始化後執行;外掛模式還需匯入本頁列出的 Facade 擴充。

TypeScript
const source = univerAPI.createWorkbook({  id: 'sales-workbook',  name: 'Sales.xlsx',  sheetOrder: ['sales-data'],  sheets: {    'sales-data': {      id: 'sales-data',      name: 'Data',      rowCount: 100,      columnCount: 20,      cellData: {        0: { 0: { v: 100 } },        1: { 0: { v: 200 } },      },    },  },}, { makeCurrent: false })const report = univerAPI.createWorkbook({ id: 'report-workbook', name: 'Report' })const resultCell = report.getActiveSheet().getRange('A1')resultCell.setFormula("=SUM('[Sales.xlsx]Data'!A1:A2)")const formula = univerAPI.getFormula()formula.executeCalculation()await formula.onCalculationResultApplied()console.log(resultCell.getValue()) // 300

makeCurrent: false 載入來源時不切換目前活頁簿。保留 source、report 可避免切換目前活頁簿後寫入錯誤位置。

名稱比對不區分大小寫,完整名稱優先;找不到時才忽略 .xlsx、.xlsm 等 Excel 副檔名。名稱不存在或不唯一時返回 #REF!,因此來源名稱應明確且唯一。

綁定固定的來源 ID

需要將公式名稱綁定到穩定文件 ID 時,可使用 @univerjs-pro/engine-formula。這是 Pro 擴充:先設定用戶端授權,初始化時以 UniverProFormulaEnginePlugin 取代 UniverFormulaEnginePlugin,並匯入 Pro Facade。不要同時註冊兩個引擎;僅匯入 Facade 不會註冊外掛。

以下範例在已設定 Pro 引擎的環境中沿用上述活頁簿:

TypeScript
import '@univerjs-pro/engine-formula/facade'const reference = univerAPI.getFormula().buildReference({  hostUnitId: report.getId(),  unit: {    unitId: source.getId(),    formulaQualifier: 'Sales Source',  },  target: {    kind: univerAPI.Enum.FormulaReferenceType.SHEET_RANGE,    sheetName: 'Data',    range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 },  },})resultCell.setFormula(`=SUM(${reference})`)

hostUnitId 是儲存公式的活頁簿 ID,unit.unitId 是來源的穩定 ID,formulaQualifier 是公式中的公開名稱。座標從 0 開始,包含結束座標。

buildReference() 傳回不含 = 的引用片段並儲存綁定,不會載入來源或開始計算。資料仍需來自計算環境中已載入的活頁簿或已設定的資料提供者。手寫或由應用程式產生的公式應先綁定:

TypeScript
const formula = univerAPI.getFormula()const bound = formula.upsertExternalReference({  unitId: report.getId(),  qualifier: 'Sales Source',  sourceUnitId: source.getId(),  sourceUnitType: univerAPI.Enum.UniverInstanceType.UNIVER_SHEET,})if (!bound) throw new Error('Could not bind Sales Source')resultCell.setFormula("=SUM('[Sales Source]Data'!A1:A2)")

相同綁定重複寫入是冪等操作。qualifier 不含括號或引號,也不可使用 1、2 等正整數;它們是 Excel 外部連結槽位,並非業務文件 ID。匯入外部連結時需保留連結資源,只複製公式文字並不足夠。

更新、儲存與卸載

透過 Facade 更新來源後,明確觸發計算並等待結果寫回,再讀取目標。不要假定 setFormula() 或 setValue() 返回時非同步計算已完成。

TypeScript
const sourceSheet = source.getSheetBySheetId('sales-data')if (!sourceSheet) throw new Error('Source sheet not found')sourceSheet.getRange('A1').setValue(150)formula.executeCalculation()await formula.onCalculationResultApplied()console.log(resultCell.getValue()) // 350

使用 report.save() 儲存含引用綁定資源的完整快照。只儲存公式文字會遺失名稱與來源 ID 的映射;來源資料需要另外儲存與載入。

來源卸載後,一般的已載入活頁簿引用無法再讀取它。Pro 引用能否繼續計算取決於資料提供者與可用快取;綁定不包含來源資料,也不保證離線計算。先前顯示的值不代表最新結果。

不再需要 Pro 綁定時可移除:

TypeScript
univerAPI.getFormula().removeExternalReference({  unitId: report.getId(),  qualifier: 'Sales Source',})

移除綁定不會刪除或改寫公式。下次計算重新解析名稱:若仍有同名的已載入活頁簿,可能繼續解析,否則返回 #REF!。若要停止引用,也應修改或清除公式。完整參數見 FFormula 引用綁定 API。

三維引用

三維引用涵蓋同一活頁簿內連續的工作表,與跨活頁簿引用不同:

text
=SUM(Jan:Mar!B2:C3)=SUM('Jan':'Mar'!B2)

範圍包含 Jan、Mar 與兩者之間的所有工作表,按活頁簿順序而非名稱排序。調整工作表順序時,應檢查彙總範圍是否仍正確。

已經支援的公式函數

Functions - (528)
ARRAY_CONSTRAINConstrains an array result to a specified size.
FLATTENFlattens all the values from one or more ranges into a single column.
BETADISTReturns the cumulative beta probability density function. The beta distribution is commonly used to study variation in the percentage of something across samples, such as the fraction of the day people spend watching television.
BETAINVReturns the inverse of the cumulative beta probability density function for a specified beta distribution. That is, if probability = BETADIST(x,...), then BETAINV(probability,...) = x. The beta distribution can be used in project planning to model probable completion times given an expected completion time and variability.
BINOMDISTReturns the individual term binomial distribution probability. Use BINOMDIST in problems with a fixed number of tests or trials, when the outcomes of any trial are only success or failure, when trials are independent, and when the probability of success is constant throughout the experiment. For example, BINOMDIST can calculate the probability that two of the next three babies born are male.
CHIDISTReturns the right-tailed probability of the chi-squared distribution. The χ2 distribution is associated with a χ2 test. Use the χ2 test to compare observed and expected values. For example, a genetic experiment might hypothesize that the next generation of plants will exhibit a certain set of colors. By comparing the observed results with the expected ones, you can decide whether your original hypothesis is valid.
CHIINVReturns the inverse of the right-tailed probability of the chi-squared distribution. If probability = CHIDIST(x,...), then CHIINV(probability,...) = x. Use this function to compare observed results with expected ones in order to decide whether your original hypothesis is valid.
CHITESTReturns the test for independence. CHITEST returns the value from the chi-squared (χ2) distribution for the statistic and the appropriate degrees of freedom. You can use χ2 tests to determine whether hypothesized results are verified by an experiment.
CONFIDENCEReturns the confidence interval for a population mean, using a normal distribution.
COVARReturns covariance, the average of the products of deviations for each data point pair in two data sets.
CRITBINOMReturns the smallest value for which the cumulative binomial distribution is greater than or equal to a criterion value. Use this function for quality assurance applications. For example, use CRITBINOM to determine the greatest number of defective parts that are allowed to come off an assembly line run without rejecting the entire lot.
EXPONDISTReturns the exponential distribution. Use EXPONDIST to model the time between events, such as how long an automated bank teller takes to deliver cash. For example, you can use EXPONDIST to determine the probability that the process takes at most 1 minute.
FDISTReturns the (right-tailed) F probability distribution (degree of diversity) for two data sets. You can use this function to determine whether two data sets have different degrees of diversity. For example, you can examine the test scores of men and women entering high school and determine if the variability in the females is different from that found in the males.
FINVReturns the inverse of the (right-tailed) F probability distribution. If p = FDIST(x,...), then FINV(p,...) = x.
FTESTReturns the result of an F-test. An F-test returns the two-tailed probability that the variances in array1 and array2 are not significantly different. Use this function to determine whether two samples have different variances. For example, given test scores from public and private schools, you can test whether these schools have different levels of test score diversity.
GAMMADISTReturns the gamma distribution. You can use this function to study variables that may have a skewed distribution. The gamma distribution is commonly used in queuing analysis.
GAMMAINVReturns the inverse of the gamma cumulative distribution. If p = GAMMADIST(x,...), then GAMMAINV(p,...) = x. You can use this function to study a variable whose distribution may be skewed.
HYPGEOMDISTReturns the hypergeometric distribution. HYPGEOMDIST returns the probability of a given number of sample successes, given the sample size, population successes, and population size. Use HYPGEOMDIST for problems with a finite population, where each observation is either a success or a failure, and where each subset of a given size is chosen with equal likelihood.
LOGINVReturns the inverse of the lognormal cumulative distribution function of x, where ln(x) is normally distributed with parameters mean and standard_dev. If p = LOGNORMDIST(x,...) then LOGINV(p,...) = x.
LOGNORMDISTReturns the cumulative lognormal distribution of x, where ln(x) is normally distributed with parameters mean and standard_dev. Use this function to analyze data that has been logarithmically transformed.
MODELet's say you want to find out the most common number of bird species sighted in a sample of bird counts at a critical wetland over a 30-year time period, or you want to find out the most frequently occurring number of phone calls at a telephone support center during off-peak hours. To calculate the mode of a group of numbers, use the MODE function.
NEGBINOMDISTReturns the negative binomial distribution. NEGBINOMDIST returns the probability that there will be number_f failures before the number_s-th success, when the constant probability of a success is probability_s. This function is similar to the binomial distribution, except that the number of successes is fixed, and the number of trials is variable. Like the binomial, trials are assumed to be independent.
NORMDISTThe NORMDIST function returns the normal distribution for the specified mean and standard deviation. This function has a wide range of applications in statistics, including hypothesis testing.
NORMINVReturns the inverse of the normal cumulative distribution for the specified mean and standard deviation.
NORMSDISTReturns the standard normal cumulative distribution function. The distribution has a mean of 0 (zero) and a standard deviation of one. Use this function in place of a table of standard normal curve areas.
NORMSINVReturns the inverse of the standard normal cumulative distribution. The distribution has a mean of zero and a standard deviation of one.
PERCENTILEReturns the k-th percentile of values in a range. You can use this function to establish a threshold of acceptance. For example, you can decide to examine candidates who score above the 90th percentile.
PERCENTRANKThe PERCENTRANK function returns the rank of a value in a dataset as a percentage of the dataset -- essentially, the relative standing of a value within the whole dataset. For example, you could use PERCENTRANK to determine the standing of an individual's test score among the field of all scores for the same test.
POISSONReturns the Poisson distribution. A common application of the Poisson distribution is predicting the number of events over a specific time, such as the number of cars arriving at a toll plaza in 1 minute.
QUARTILEReturns the quartile of a data set. Quartiles often are used in sales and survey data to divide populations into groups. For example, you can use QUARTILE to find the top 25 percent of incomes in a population.
RANKReturns the rank of a number in a list of numbers. The rank of a number is its size relative to other values in a list. (If you were to sort the list, the rank of the number would be its position.)
STDEVEstimates standard deviation based on a sample. The standard deviation is a measure of how widely values are dispersed from the average value (the mean).
STDEVPCalculates standard deviation based on the entire population given as arguments. The standard deviation is a measure of how widely values are dispersed from the average value (the mean).
TDISTReturns the Percentage Points (probability) for the Student t-distribution where a numeric value (x) is a calculated value of t for which the Percentage Points are to be computed. The t-distribution is used in the hypothesis testing of small sample data sets. Use this function in place of a table of critical values for the t-distribution.
TINVReturns the two-tailed inverse of the Student's t-distribution.
TTESTReturns the probability associated with a Student's t-Test. Use TTEST to determine whether two samples are likely to have come from the same two underlying populations that have the same mean.
VAREstimates variance based on a sample.
VARPCalculates variance based on the entire population.
WEIBULLReturns the Weibull distribution. Use this distribution in reliability analysis, such as calculating a device's mean time to failure.
ZTESTReturns the one-tailed probability-value of a z-test. For a given hypothesized population mean, μ0, ZTEST returns the probability that the sample mean would be greater than the average of observations in the data set (array) — that is, the observed sample mean.
CUBEKPIMEMBERReturns a key performance indicator (KPI) property and displays the KPI name in the cell. A KPI is a quantifiable measurement, such as monthly gross profit or quarterly employee turnover, that is used to monitor an organization's performance.
CUBEMEMBERReturns a member or tuple from the cube. Use to validate that the member or tuple exists in the cube.
CUBEMEMBERPROPERTYThe CUBEMEMBERPROPERTY function, one of the Cube functions in Excel, returns the value of a member property from a cube. Use it to validate that a member name exists within the cube, and to return the specified property for this member.
CUBERANKEDMEMBERReturns the nth, or ranked, member in a set. Use to return one or more elements in a set, such as the top sales performer or the top 10 students.
CUBESETDefines a calculated set of members or tuples by sending a set expression to the cube on the server, which creates the set, and then returns that set to Microsoft Excel.
CUBESETCOUNTReturns the number of items in a set.
CUBEVALUEReturns an aggregated value from the cube.
DAVERAGEAverages the values in a field (column) of records in a list or database that match conditions you specify.
DCOUNTCounts the cells that contain numbers in a field (column) of records in a list or database that match conditions that you specify.
DCOUNTACounts the nonblank cells in a field (column) of records in a list or database that match conditions that you specify.
DGETExtracts a single value from a column of a list or database that matches conditions that you specify.
DMAXReturns the largest number in a field (column) of records in a list or database that matches conditions you that specify.
DMINReturns the smallest number in a field (column) of records in a list or database that matches conditions that you specify.
DPRODUCTMultiplies the values in a field (column) of records in a list or database that match conditions that you specify.
DSTDEVEstimates the standard deviation of a population based on a sample by using the numbers in a field (column) of records in a list or database that match conditions that you specify.
DSTDEVPCalculates the standard deviation of a population based on the entire population by using the numbers in a field (column) of records in a list or database that match conditions that you specify.
DSUMIn a list or database, DSUM provides the sum of the numbers in fields (columns) of records that match your specified conditions.
DVAREstimates the variance of a population based on a sample by using the numbers in a field (column) of records in a list or database that match conditions that you specify.
DVARPCalculates the variance of a population based on the entire population by using the numbers in a field (column) of records in a list or database that match conditions that you specify.
DATEReturns the serial number of a particular date
DATEDIFCalculates the number of days, months, or years between two dates. This function is useful in formulas where you need to calculate an age.
DATEVALUEConverts a date in the form of text to a serial number.
DAYReturns the day of a date, represented by a serial number. The day is given as an integer ranging from 1 to 31.
DAYSReturns the number of days between two dates.
DAYS360Calculates the number of days between two dates based on a 360-day year
EDATEReturns the serial number that represents the date that is the indicated number of months before or after a specified date (the start_date). Use EDATE to calculate maturity dates or due dates that fall on the same day of the month as the date of issue.
EOMONTHReturns the serial number of the last day of the month before or after a specified number of months
EPOCHTODATEConverts a Unix epoch timestamp in seconds, milliseconds, or microseconds to a datetime in Universal Time Coordinated (UTC).
HOURConverts a serial number to an hour
ISOWEEKNUMReturns the number of the ISO week number of the year for a given date
MINUTEReturns the minutes of a time value. The minute is given as an integer, ranging from 0 to 59.
MONTHReturns the month of a date represented by a serial number. The month is given as an integer, ranging from 1 (January) to 12 (December).
NETWORKDAYSReturns the number of whole working days between start_date and end_date. Working days exclude weekends and any dates identified in holidays. Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days worked during a specific term.
NETWORKDAYS_INTLReturns the number of whole workdays between two dates using parameters to indicate which and how many days are weekend days
NOWReturns the serial number of the current date and time. If the cell format was General before the function was entered, Excel changes the cell format so that it matches the date and time format of your regional settings. You can change the date and time format for the cell by using the commands in the Number group of the Home tab on the Ribbon.
SECONDReturns the seconds of a time value. The second is given as an integer in the range 0 (zero) to 59.
TIMEReturns the decimal number for a particular time. If the cell format was General before the function was entered, the result is formatted as a date.
TIMEVALUEConverts a time in the form of text to a serial number.
TO_DATEConverts a provided number to a date.
TODAYReturns the serial number of today's date
WEEKDAYConverts a serial number to a day of the week
WEEKNUMConverts a serial number to a number representing where the week falls numerically with a year
WORKDAYReturns the serial number of the date before or after a specified number of workdays
WORKDAY_INTLReturns the serial number of the date before or after a specified number of workdays using parameters to indicate which and how many days are weekend days
YEARReturns the year corresponding to a date. The year is returned as an integer in the range 1900-9999.
YEARFRACReturns the year fraction representing the number of whole days between start_date and end_date
BESSELIReturns the modified Bessel function In(x)
BESSELJReturns the Bessel function Jn(x)
BESSELKReturns the modified Bessel function Kn(x)
BESSELYReturns the Bessel function Yn(x)
BIN2DECConverts a binary number to decimal
BIN2HEXConverts a binary number to hexadecimal
BIN2OCTConverts a binary number to octal.
BITANDReturns a bitwise 'AND' of two numbers.
BITLSHIFTReturns a value number shifted left by shift_amount bits
BITORReturns a bitwise OR of 2 numbers
BITRSHIFTReturns a value number shifted right by shift_amount bits
BITXORReturns a bitwise 'Exclusive Or' of two numbers
COMPLEXConverts real and imaginary coefficients into a complex number
CONVERTConverts a number from one measurement system to another
DEC2BINConverts a decimal number to binary
DEC2HEXConverts a decimal number to hexadecimal
DEC2OCTConverts a decimal number to octal
DELTATests whether two values are equal
ERFReturns the error function
ERF_PRECISEReturns the error function
ERFCReturns the complementary error function
ERFC_PRECISEReturns the complementary ERF function integrated between x and infinity
GESTEPTests whether a number is greater than a threshold value
HEX2BINConverts a hexadecimal number to binary
HEX2DECConverts a hexadecimal number to decimal
HEX2OCTConverts a hexadecimal number to octal
IMABSReturns the absolute value (modulus) of a complex number
IMAGINARYReturns the imaginary coefficient of a complex number
IMARGUMENTReturns the argument theta, an angle expressed in radians
IMCONJUGATEReturns the complex conjugate of a complex number
IMCOSReturns the cosine of a complex number
IMCOSHReturns the hyperbolic cosine of a complex number
IMCOTReturns the cotangent of a complex number
IMCOTHThe IMCOTH function returns the hyperbolic cotangent of the given complex number. For example, a given complex number "x+yi" returns "coth(x+yi)."
IMCSCReturns the cosecant of a complex number
IMCSCHReturns the hyperbolic cosecant of a complex number
IMDIVReturns the quotient of two complex numbers in x + yi or x + yj text format.
IMEXPReturns the exponential of a complex number in x + yi or x + yj text format.
IMLNReturns the natural logarithm of a complex number
IMLOGThe IMLOG function returns the logarithm of a complex number for a specified base.
IMLOG10Returns the base-10 logarithm of a complex number
IMLOG2Returns the base-2 logarithm of a complex number
IMPOWERReturns a complex number raised to an integer power
IMPRODUCTReturns the product of from 1 to 255 complex numbers
IMREALReturns the real coefficient of a complex number
IMSECReturns the secant of a complex number
IMSECHReturns the hyperbolic secant of a complex number
IMSINReturns the sine of a complex number
IMSINHReturns the hyperbolic sine of a complex number
IMSQRTReturns the square root of a complex number
IMSUBReturns the difference between two complex numbers
IMSUMReturns the sum of complex numbers
IMTANReturns the tangent of a complex number
IMTANHThe IMTANH function returns the hyperbolic tangent of the given complex number. For example, a given complex number "x+yi" returns "tanh(x+yi)."
OCT2BINConverts an octal number to binary
OCT2DECConverts an octal number to decimal
OCT2HEXConverts an octal number to hexadecimal
ACCRINTReturns the accrued interest for a security that pays periodic interest
ACCRINTMReturns the accrued interest for a security that pays interest at maturity
AMORDEGRCReturns the depreciation for each accounting period by using a depreciation coefficient
AMORLINCReturns the depreciation for each accounting period
COUPDAYBSReturns the number of days from the beginning of the coupon period to the settlement date
COUPDAYSReturns the number of days in the coupon period that contains the settlement date
COUPDAYSNCReturns the number of days from the settlement date to the next coupon date
COUPNCDReturns the next coupon date after the settlement date
COUPNUMReturns the number of coupons payable between the settlement date and maturity date
COUPPCDReturns the previous coupon date before the settlement date
CUMIPMTReturns the cumulative interest paid between two periods
CUMPRINCReturns the cumulative principal paid on a loan between two periods
DBReturns the depreciation of an asset for a specified period by using the fixed-declining balance method
DDBReturns the depreciation of an asset for a specified period by using the double-declining balance method or some other method that you specify
DISCReturns the discount rate for a security
DOLLARDEConverts a dollar price, expressed as a fraction, into a dollar price, expressed as a decimal number
DOLLARFRConverts a dollar price, expressed as a decimal number, into a dollar price, expressed as a fraction
DURATIONReturns the annual duration of a security with periodic interest payments
EFFECTReturns the effective annual interest rate, given the nominal annual interest rate and the number of compounding periods per year.
FVReturns the future value of an investment
FVSCHEDULEReturns the future value of an initial principal after applying a series of compound interest rates
INTRATEReturns the interest rate for a fully invested security.
IPMTReturns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
IRRReturns the internal rate of return for a series of cash flows
ISPMTCalculates the interest paid during a specific period of an investment
MDURATIONReturns the Macauley modified duration for a security with an assumed par value of $100
MIRRReturns the internal rate of return where positive and negative cash flows are financed at different rates
NOMINALReturns the annual nominal interest rate
NPERReturns the number of periods for an investment
NPVReturns the net present value of an investment based on a series of periodic cash flows and a discount rate
ODDFPRICEReturns the price per $100 face value of a security with an odd first period
ODDFYIELDReturns the yield of a security with an odd first period
ODDLPRICEReturns the price per $100 face value of a security with an odd last period
ODDLYIELDReturns the yield of a security with an odd last period
PDURATIONReturns the number of periods required by an investment to reach a specified value
PMTReturns the periodic payment for an annuity
PPMTReturns the payment on the principal for an investment for a given period
PRICEReturns the price per $100 face value of a security that pays periodic interest
PRICEDISCReturns the price per $100 face value of a discounted security
PRICEMATReturns the price per $100 face value of a security that pays interest at maturity
PVReturns the present value of an investment
RATEReturns the interest rate per period of an annuity
RECEIVEDReturns the amount received at maturity for a fully invested security
RRIReturns an equivalent interest rate for the growth of an investment
SLNReturns the straight-line depreciation of an asset for one period
SYDReturns the sum-of-years' digits depreciation of an asset for a specified period
TBILLEQReturns the bond-equivalent yield for a Treasury bill
TBILLPRICEReturns the price per $100 face value for a Treasury bill
TBILLYIELDReturns the yield for a Treasury bill
VDBReturns the depreciation of an asset for a specified or partial period by using a declining balance method
XIRRReturns the internal rate of return for a schedule of cash flows that is not necessarily periodic
XNPVReturns the net present value for a schedule of cash flows that is not necessarily periodic
YIELDReturns the yield on a security that pays periodic interest
YIELDDISCReturns the annual yield for a discounted security; for example, a Treasury bill
YIELDMATReturns the annual yield of a security that pays interest at maturity
CELLReturns information about the formatting, location, or contents of a cell
ERROR_TYPEReturns a number corresponding to an error type
INFOReturns information about the current operating environment
ISBETWEENChecks whether a provided number is between two other numbers either inclusively or exclusively.
ISBLANKReturns TRUE if the value is blank
ISDATEThe ISDATE function returns whether a value is a date.
ISEMAILTo check if a value is a valid email address, use the ISEMAIL function. This checks if the value follows a commonly accepted format for email addresses but doesn’t verify its existence.
ISERRReturns TRUE if the value is any error value except #N/A
ISERRORReturns TRUE if the value is any error value
ISEVENReturns TRUE if number is even, or FALSE if number is odd.
ISFORMULAReturns TRUE if there is a reference to a cell that contains a formula
ISLOGICALReturns TRUE if the value is a logical value
ISNAReturns TRUE if the value is the #N/A error value
ISNONTEXTReturns TRUE if the value is not text
ISNUMBERReturns TRUE if the value is a number
ISODDReturns TRUE if the number is odd
ISOMITTEDChecks whether the value in a LAMBDA is missing and returns TRUE or FALSE
ISREFReturns TRUE if the value is a reference
ISTEXTReturns TRUE if the value is text
ISURLChecks whether a value is a valid URL.
NReturns a value converted to a number
NAReturns the error value #N/A
SHEETReturns the sheet number of the referenced sheet
SHEETSReturns the number of sheets in a workbook
TYPEReturns a number indicating the data type of a value
ANDReturns TRUE if all of its arguments are TRUE
BYCOLApplies a LAMBDA to each column and returns an array of the results
BYROWApplies a LAMBDA to each row and returns an array of the results
FALSEReturns the logical value FALSE.
IFSpecifies a logical test to perform
IFERRORReturns a value you specify if a formula evaluates to an error; otherwise, returns the result of the formula
IFNAReturns the value you specify if the expression resolves to #N/A, otherwise returns the result of the expression
IFSChecks whether one or more conditions are met and returns a value that corresponds to the first TRUE condition.
LAMBDAUse a LAMBDA function to create custom, reusable functions and call them by a friendly name. The new function is available throughout the workbook and called like native Excel functions.
LETAssigns names to calculation results
MAKEARRAYReturns a calculated array of a specified row and column size, by applying a LAMBDA
MAPReturns an array formed by mapping each value in the array(s) to a new value by applying a LAMBDA to create a new value.
NOTReverses the logic of its argument.
ORReturns TRUE if any of its arguments evaluate to TRUE, and returns FALSE if all of its arguments evaluate to FALSE.
REDUCEReduces an array to an accumulated value by applying a LAMBDA to each value and returning the total value in the accumulator.
SCANScans an array by applying a LAMBDA to each value and returns an array that has each intermediate value.
SWITCHEvaluates an expression against a list of values and returns the result corresponding to the first matching value. If there is no match, an optional default value may be returned.
TRUEReturns the logical value TRUE.
XORReturns TRUE if an odd number of its arguments evaluate to TRUE, and FALSE if an even number of its arguments evaluate to TRUE.
ADDRESSObtain the address of a cell in a worksheet, given specified row and column numbers. For example, ADDRESS(2,3) returns $C$2. As another example, ADDRESS(77,300) returns $KN$77. You can use other functions, such as the ROW and COLUMN functions, to provide the row and column number arguments for the ADDRESS function.
AREASReturns the number of areas in a reference
CHOOSEChooses a value from a list of values.
CHOOSECOLSReturns the specified columns from an array
CHOOSEROWSReturns the specified rows from an array
COLUMNReturns the column number of the given cell reference.
COLUMNSReturns the number of columns in an array or reference.
DROPExcludes a specified number of rows or columns from the start or end of an array
EXPANDExpands or pads an array to specified row and column dimensions
FILTERThe FILTER function allows you to filter a range of data based on criteria you define.
FORMULATEXTReturns the formula at the given reference as text
GETPIVOTDATAReturns data stored in a PivotTable report
HLOOKUPSearches for a value in the top row of a table or an array of values, and then returns a value in the same column from a row you specify in the table or array. Use HLOOKUP when your comparison values are located in a row across the top of a table of data, and you want to look down a specified number of rows. Use VLOOKUP when your comparison values are located in a column to the left of the data you want to find.
HSTACKAppends arrays horizontally and in sequence to return a larger array
HYPERLINKCreates a hyperlink inside a cell.
IMAGECurrent Channel
INDEXThe INDEX function returns a value or the reference to a value from within a table or range.
INDIRECTReturns the reference specified by a text string. References are immediately evaluated to display their contents.
LOOKUPWhen you need to look in a single row or column and find a value from the same position in a second row or column
MATCHThe MATCH function searches for a specified item in a range of cells, and then returns the relative position of that item in the range.
OFFSETReturns a reference offset from a given reference
ROWReturns the row number of a reference
ROWSReturns the number of rows in an array or reference.
RTDRetrieves real-time data from a program that supports COM automation
SORTSorts the contents of a range or array
SORTBYSorts the contents of a range or array based on the values in a corresponding range or array
TAKEReturns a specified number of contiguous rows or columns from the start or end of an array
TOCOLReturns the array in a single column
TOROWReturns the array in a single row
TRANSPOSEReturns the transpose of an array
UNIQUEReturns a list of unique values in a list or range
VLOOKUPUse VLOOKUP when you need to find things in a table or a range by row. For example, look up a price of an automotive part by the part number, or find an employee name based on their employee ID.
VSTACKAppends arrays vertically and in sequence to return a larger array
WRAPCOLSWraps the provided row or column of values by columns after a specified number of elements
WRAPROWSWraps the provided row or column of values by rows after a specified number of elements
XLOOKUPSearches a range or an array, and returns an item corresponding to the first match it finds. If a match doesn't exist, then XLOOKUP can return the closest (approximate) match.
XMATCHSearches for a specified item in an array or range of cells, and then returns the item's relative position.
ABSReturns the absolute value of a number. The absolute value of a number is the number without its sign.
ACOSReturns the arccosine, or inverse cosine, of a number. The arccosine is the angle whose cosine is number. The returned angle is given in radians in the range 0 (zero) to pi.
ACOSHReturns the inverse hyperbolic cosine of a number. The number must be greater than or equal to 1. The inverse hyperbolic cosine is the value whose hyperbolic cosine is number, so ACOSH(COSH(number)) equals number.
ACOTReturns the principal value of the arccotangent, or inverse cotangent, of a number.
ACOTHReturns the hyperbolic arccotangent of a number
AGGREGATEReturns an aggregate in a list or database
ARABICConverts a Roman numeral to an Arabic numeral.
ASINReturns the arcsine, or inverse sine, of a number. The arcsine is the angle whose sine is number . The returned angle is given in radians in the range -pi/2 to pi/2.
ASINHReturns the inverse hyperbolic sine of a number. The inverse hyperbolic sine is the value whose hyperbolic sine is number , so ASINH(SINH(number)) equals number .
ATANReturns the arctangent of a number.
ATAN2Returns the arctangent from x- and y-coordinates.
ATANHReturns the inverse hyperbolic tangent of a number. Number must be between -1 and 1 (excluding -1 and 1). The inverse hyperbolic tangent is the value whose hyperbolic tangent is number , so ATANH(TANH(number)) equals number .
BASEConverts a number into a text representation with the given radix (base).
CEILINGRounds a number to the nearest integer or to the nearest multiple of significance
CEILING_MATHRounds a number up, to the nearest integer or to the nearest multiple of significance
CEILING_PRECISERounds a number the nearest integer or to the nearest multiple of significance. Regardless of the sign of the number, the number is rounded up.
COMBINReturns the number of combinations for a given number of objects
COMBINAReturns the number of combinations with repetitions for a given number of items
COSReturns the cosine of a number.
COSHReturns the hyperbolic cosine of a number
COTReturns the cotangent of an angle
COTHReturns the hyperbolic cotangent of a number
CSCReturns the cosecant of an angle
CSCHReturns the hyperbolic cosecant of an angle
DECIMALConverts a text representation of a number in a given base into a decimal number
DEGREESConverts radians to degrees
EVENRounds a number up to the nearest even integer
EXPReturns e raised to the power of a given number
FACTReturns the factorial of a number
FACTDOUBLEReturns the double factorial of a number
FLOORRounds a number down, toward zero
FLOOR_MATHRounds a number down, to the nearest integer or to the nearest multiple of significance
FLOOR_PRECISERounds a number down to the nearest integer or to the nearest multiple of significance. Regardless of the sign of the number, the number is rounded down.
GCDReturns the greatest common divisor
INTRounds a number down to the nearest integer
ISO_CEILINGReturns a number that is rounded up to the nearest integer or to the nearest multiple of significance
LCMReturns the least common multiple
LNReturns the natural logarithm of a number
LOGReturns the logarithm of a number to a specified base
LOG10Returns the base-10 logarithm of a number
MDETERMReturns the matrix determinant of an array
MINVERSEReturns the matrix inverse of an array
MMULTReturns the matrix product of two arrays
MODReturns the remainder after number is divided by divisor. The result has the same sign as divisor.
MROUNDReturns a number rounded to the desired multiple
MULTINOMIALReturns the multinomial of a set of numbers
MUNITReturns the unit matrix or the specified dimension
ODDRounds a number up to the nearest odd integer
PIReturns the value of pi
POWERReturns the result of a number raised to a power.
PRODUCTMultiplies all the numbers given as arguments and returns the product.
QUOTIENTReturns the integer portion of a division
RADIANSConverts degrees to radians
RANDReturns a random number between 0 and 1
RANDARRAYReturns an array of random numbers between 0 and 1. However, you can specify the number of rows and columns to fill, minimum and maximum values, and whether to return whole numbers or decimal values.
RANDBETWEENReturns a random number between the numbers you specify
ROMANConverts an Arabic numeral to Roman, as text
ROUNDRounds a number to a specified number of digits
ROUNDBANKRounds a number in banker's rounding
ROUNDDOWNRounds a number down, toward zero
ROUNDUPRounds a number up, away from zero
SECReturns the secant of an angle
SECHReturns the hyperbolic secant of an angle
SERIESSUMReturns the sum of a power series based on the formula
SEQUENCEGenerates a list of sequential numbers in an array, such as 1, 2, 3, 4
SIGNReturns the sign of a number
SINReturns the sine of the given angle
SINHReturns the hyperbolic sine of a number
SQRTReturns a positive square root
SQRTPIReturns the square root of (number * pi)
SUBTOTALReturns a subtotal in a list or database.
SUMYou can add individual values, cell references or ranges or a mix of all three.
SUMIFSum the values in a range that meet criteria that you specify.
SUMIFSAdds all of its arguments that meet multiple criteria.
SUMPRODUCTReturns the sum of the products of corresponding array components
SUMSQReturns the sum of the squares of the arguments
SUMX2MY2Returns the sum of the difference of squares of corresponding values in two arrays
SUMX2PY2Returns the sum of the sum of squares of corresponding values in two arrays
SUMXMY2Returns the sum of squares of differences of corresponding values in two arrays
TANReturns the tangent of a number.
TANHReturns the hyperbolic tangent of a number.
TRUNCTruncates a number to an integer
AVEDEVReturns the average of the absolute deviations of data points from their mean.
AVERAGEReturns the average (arithmetic mean) of the arguments.
AVERAGE_WEIGHTEDThe AVERAGE.WEIGHTED function finds the weighted average of a set of values, given the values and the corresponding weights.
AVERAGEAReturns the average of its arguments, including numbers, text, and logical values.
AVERAGEIFReturns the average (arithmetic mean) of all the cells in a range that meet a given criteria.
AVERAGEIFSReturns the average (arithmetic mean) of all cells that meet multiple criteria.
BETA_DISTReturns the beta cumulative distribution function
BETA_INVReturns the inverse of the cumulative distribution function for a specified beta distribution
BINOM_DISTReturns the individual term binomial distribution probability
BINOM_DIST_RANGEReturns the probability of a trial result using a binomial distribution
BINOM_INVReturns the smallest value for which the cumulative binomial distribution is less than or equal to a criterion value
CHISQ_DISTReturns the left-tailed probability of the chi-squared distribution.
CHISQ_DIST_RTReturns the right-tailed probability of the chi-squared distribution.
CHISQ_INVReturns the inverse of the left-tailed probability of the chi-squared distribution.
CHISQ_INV_RTReturns the inverse of the right-tailed probability of the chi-squared distribution.
CHISQ_TESTReturns the test for independence
CONFIDENCE_NORMReturns the confidence interval for a population mean, using a normal distribution.
CONFIDENCE_TReturns the confidence interval for a population mean, using a Student's t distribution
CORRELReturns the correlation coefficient between two data sets
COUNTCounts the number of cells that contain numbers, and counts numbers within the list of arguments.
COUNTACounts cells containing any type of information, including error values and empty text ("") If you do not need to count logical values, text, or error values
COUNTBLANKCounts the number of blank cells within a range.
COUNTIFCounts the number of cells within a range that meet the given criteria.
COUNTIFSCounts the number of cells within a range that meet multiple criteria.
COVARIANCE_PReturns population covariance, the average of the products of deviations for each data point pair in two data sets.
COVARIANCE_SReturns the sample covariance, the average of the products of deviations for each data point pair in two data sets.
DEVSQReturns the sum of squares of deviations
EXPON_DISTReturns the exponential distribution
F_DISTReturns the F probability distribution
F_DIST_RTReturns the (right-tailed) F probability distribution
F_INVReturns the inverse of the F probability distribution
F_INV_RTReturns the inverse of the (right-tailed) F probability distribution
F_TESTReturns the result of an F-test
FISHERReturns the Fisher transformation
FISHERINVReturns the inverse of the Fisher transformation
FORECASTReturns a value along a linear trend
FORECAST_ETSReturns a future value based on existing (historical) values by using the AAA version of the Exponential Smoothing (ETS) algorithm
FORECAST_ETS_CONFINTReturns a confidence interval for the forecast value at the specified target date
FORECAST_ETS_SEASONALITYReturns the length of the repetitive pattern Excel detects for the specified time series
FORECAST_ETS_STATReturns a statistical value as a result of time series forecasting
FORECAST_LINEARReturns a future value based on existing values
FREQUENCYReturns a frequency distribution as a vertical array
GAMMAReturns the Gamma function value
GAMMA_DISTReturns the gamma distribution
GAMMA_INVReturns the inverse of the gamma cumulative distribution
GAMMALNReturns the natural logarithm of the gamma function, Γ(x)
GAMMALN_PRECISEReturns the natural logarithm of the gamma function, Γ(x)
GAUSSReturns 0.5 less than the standard normal cumulative distribution
GEOMEANReturns the geometric mean
GROWTHReturns values along an exponential trend
HARMEANReturns the harmonic mean
HYPGEOM_DISTReturns the hypergeometric distribution
INTERCEPTReturns the intercept of the linear regression line
KURTReturns the kurtosis of a data set
LARGEReturns the k-th largest value in a data set
LINESTReturns the parameters of a linear trend
LOGESTReturns the parameters of an exponential trend
LOGNORM_DISTReturns the cumulative lognormal distribution
LOGNORM_INVReturns the inverse of the lognormal cumulative distribution
MARGINOFERRORThis function calculates the margin of error from a range of values and a confidence level.
MAXReturns the largest value in a set of values.
MAXAReturns the maximum value in a list of arguments, including numbers, text, and logical values.
MAXIFSReturns the maximum value among cells specified by a given set of conditions or criteria.
MEDIANReturns the median of the given numbers
MINReturns the smallest number in a set of values.
MINAReturns the smallest value in a list of arguments, including numbers, text, and logical values
MINIFSReturns the minimum value among cells specified by a given set of conditions or criteria.
MODE_MULTReturns a vertical array of the most frequently occurring, or repetitive values in an array or range of data
MODE_SNGLReturns the most common value in a data set
NEGBINOM_DISTReturns the negative binomial distribution
NORM_DISTReturns the normal cumulative distribution
NORM_INVReturns the inverse of the normal cumulative distribution
NORM_S_DISTReturns the standard normal cumulative distribution
NORM_S_INVReturns the inverse of the standard normal cumulative distribution
PEARSONReturns the Pearson product moment correlation coefficient
PERCENTILE_EXCReturns the k-th percentile of values in a data set (Excludes 0 and 1).
PERCENTILE_INCReturns the k-th percentile of values in a data set (Includes 0 and 1)
PERCENTRANK_EXCReturns the percentage rank of a value in a data set (Excludes 0 and 1)
PERCENTRANK_INCReturns the percentage rank of a value in a data set (Includes 0 and 1)
PERMUTReturns the number of permutations for a given number of objects
PERMUTATIONAReturns the number of permutations for a given number of objects (with repetitions) that can be selected from the total objects
PHIReturns the value of the density function for a standard normal distribution
POISSON_DISTReturns the Poisson distribution
PROBReturns the probability that values in a range are between two limits
QUARTILE_EXCReturns the quartile of a data set (Excludes 0 and 1)
QUARTILE_INCReturns the quartile of a data set (Includes 0 and 1)
RANK_AVGReturns the rank of a number in a list of numbers
RANK_EQReturns the rank of a number in a list of numbers
RSQReturns the square of the Pearson product moment correlation coefficient
SKEWReturns the skewness of a distribution
SKEW_PReturns the skewness of a distribution based on a population
SLOPEReturns the slope of the linear regression line
SMALLReturns the k-th smallest value in a data set
STANDARDIZEReturns a normalized value
STDEV_PCalculates standard deviation based on the entire population given as arguments (ignores logical values and text).
STDEV_SEstimates standard deviation based on a sample (ignores logical values and text in the sample).
STDEVAEstimates standard deviation based on a sample, including numbers, text, and logical values.
STDEVPACalculates standard deviation based on the entire population given as arguments, including text and logical values.
STEYXReturns the standard error of the predicted y-value for each x in the regression
T_DISTReturns the probability for the Student t-distribution
T_DIST_2TReturns the probability for the Student t-distribution (two-tailed)
T_DIST_RTReturns the probability for the Student t-distribution (right-tailed)
T_INVReturns the inverse of the probability for the Student t-distribution
T_INV_2TReturns the inverse of the probability for the Student t-distribution (two-tailed)
T_TESTReturns the probability associated with a Student's t-test
TRENDReturns values along a linear trend
TRIMMEANReturns the mean of the interior of a data set
VAR_PCalculates variance based on the entire population (ignores logical values and text in the population).
VAR_SEstimates variance based on a sample (ignores logical values and text in the sample).
VARAEstimates variance based on a sample, including numbers, text, and logical values
VARPACalculates variance based on the entire population, including numbers, text, and logical values
WEIBULL_DISTReturns the Weibull distribution
Z_TESTReturns the one-tailed probability-value of a z-test
ASCChanges full-width (double-byte) English letters or katakana within a character string to half-width (single-byte) characters
ARRAYTOTEXTReturns an array of text values from any specified range
BAHTTEXTConverts a number to text, using the ß (baht) currency format
CHARReturns the character specified by the code number
CLEANRemoves all nonprintable characters from text
CODEReturns a numeric code for the first character in a text string
CONCATCombines the text from multiple ranges and/or strings, but it doesn't provide the delimiter or IgnoreEmpty arguments.
CONCATENATEJoins several text items into one text item
DBCSChanges half-width (single-byte) English letters or katakana within a character string to full-width (double-byte) characters
DOLLARConverts a number to text using currency format
EXACTChecks to see if two text values are identical
FINDFinds one text value within another (case-sensitive)
FINDBFinds one text value within another (case-sensitive)
FIXEDFormats a number as text with a fixed number of decimals
LEFTReturns the leftmost characters from a text value
LEFTBReturns the leftmost characters from a text value
LENReturns the number of characters in a text string
LENBReturns the number of bytes used to represent the characters in a text string.
LOWERConverts text to lowercase.
MIDReturns a specific number of characters from a text string starting at the position you specify.
MIDBReturns a specific number of characters from a text string starting at the position you specify
NUMBERSTRINGConvert numbers to Chinese strings
NUMBERVALUEConverts text to number in a locale-independent manner
PHONETICExtracts the phonetic (furigana) characters from a text string
PROPERCapitalizes the first letter in each word of a text value
REGEXEXTRACTExtracts the first matching substrings according to a regular expression.
REGEXMATCHWhether a piece of text matches a regular expression.
REGEXREPLACEReplaces part of a text string with a different text string using regular expressions.
REPLACEReplaces characters within text
REPLACEBReplaces characters within text
REPTRepeats text a given number of times
RIGHTReturns the rightmost characters from a text value
RIGHTBReturns the rightmost characters from a text value
SEARCHFinds one text value within another (not case-sensitive)
SEARCHBFinds one text value within another (not case-sensitive)
SUBSTITUTESubstitutes new text for old text in a text string
TConverts its arguments to text
TEXTFormats a number and converts it to text
TEXTAFTERReturns text that occurs after given character or string
TEXTBEFOREReturns text that occurs before a given character or string
TEXTJOINText: Combines the text from multiple ranges and/or strings
TEXTSPLITSplits text strings by using column and row delimiters
TRIMRemoves all spaces from text except for single spaces between words.
UNICHARReturns the Unicode character that is references by the given numeric value
UNICODEReturns the number (code point) that corresponds to the first character of the text
UPPERConverts text to uppercase
VALUEConverts a text argument to a number
VALUETOTEXTReturns text from any specified value
CALLCalls a procedure in a dynamic link library or code resource
EUROCONVERTConverts a number to euros, converts a number from euros to a euro member currency, or converts a number from one euro member currency to another by using the euro as an intermediary (triangulation)
REGISTER_IDReturns the register ID of the specified dynamic link library (DLL) or code resource that has been previously registered
ENCODEURLThe ENCODEURL function returns a URL-encoded string, replacing certain non-alphanumeric characters with the percentage symbol (%) and a hexadecimal number.
FILTERXMLThe FILTERXML function returns specific data from XML content by using the specified xpath.
WEBSERVICEThe WEBSERVICE function returns data from a web service on the Internet or Intranet.

Facade API

完整 Facade API 請參閱 FFormula。

導入

外掛模式提示

僅外掛模式需要手動引入 Facade 套件。預設模式已內建對應的 Facade 套件,無需額外引入。

TypeScript
import '@univerjs/engine-formula/facade'import '@univerjs/sheets-formula/facade'import '@univerjs/sheets-formula-ui/facade'

開啟範圍選擇器

@univerjs/sheets-formula-ui/facade 會加入 univerAPI.showRangeSelectorDialog。如果自訂 UI 需要讓使用者選擇一個或多個儲存格範圍,可以複用公式相關面板使用的範圍選擇器。

TypeScript
const workbook = univerAPI.getActiveWorkbook()const worksheet = workbook?.getActiveSheet()if (workbook && worksheet) {  await univerAPI.showRangeSelectorDialog({    unitId: workbook.getId(),    subUnitId: worksheet.getSheetId(),    initialValue: [      {        unitId: workbook.getId(),        sheetName: worksheet.getSheetName(),        range: worksheet.getRange('A1:B2').getRange(),      },    ],    maxRangeCount: 2,    supportAcrossSheet: true,    callback: (ranges, isCancel) => {      console.log(ranges, isCancel)    },  })}

執行公式計算

TypeScript
const formulaEngine = univerAPI.getFormula()formulaEngine.executeCalculation()

停止公式計算

TypeScript
const formulaEngine = univerAPI.getFormula()formulaEngine.stopCalculation()

公式開始計算

TypeScript
// 監聽公式計算開始事件const formulaEngine = univerAPI.getFormula()formulaEngine.calculationStart((forceCalculate) => {  console.log(forceCalculate)})

公式計算中

TypeScript
// 監聽公式計算中事件const formulaEngine = univerAPI.getFormula()formulaEngine.calculationProcessing((stageInfo) => {  console.log(stageInfo)})

公式計算結束

TypeScript
// 監聽公式計算結束事件const formulaEngine = univerAPI.getFormula()formulaEngine.calculationEnd((functionsExecutedState) => {  console.log(functionsExecutedState)})

公式計算結果應用

TypeScript
// 監聽公式計算結果應用事件const formulaEngine = univerAPI.getFormula()formulaEngine.calculationResultApplied((result) => {  console.log(result)})// 等待公式計算結果應用完成await formulaEngine.onCalculationResultApplied()

設定初始化資料時公式的計算模式

TypeScript
const formulaEngine = univerAPI.getFormula()formulaEngine.setInitialFormulaComputing(CalculationMode.FORCED)

如果這個 API 在 Starting 生命週期之後呼叫,會在下次建立 Univer Sheet 時生效。

如果希望它在本次初始化 Univer Sheet 時生效,可以考慮在 Ready 生命週期之前呼叫它,比如:

TypeScript
univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, ({ stage }) => {  if (stage === LifecycleStages.Starting) {    const formulaEngine = univerAPI.getFormula()    formulaEngine.setInitialFormulaComputing(CalculationMode.FORCED)  }})

反覆運算

反覆運算依活頁簿設定,並儲存在快照的 calculationSettings 欄位中。預設關閉:循環參照公式會保留快取值,沒有快取時使用零。需要計算刻意設計的循環參照模型時,再啟用此功能。

選項預設值行為
iterativeCalculationfalse啟用循環參照的反覆運算。
maxIterations1001 到 32767 之間的整數。
maxChange0.001有限正數,表示收斂閾值。當循環群組中每個數值結果的變化量皆不超過此值時停止。

透過活頁簿 Facade 一次提交三個設定。此命令支援復原、重做與協同同步;活頁簿不存在或無法編輯時傳回 false。無效設定會正規化為預設值。

TypeScript
const workbook = univerAPI.getActiveWorkbook()if (!workbook) throw new Error('No active workbook')const applied = workbook.setCalculationSettings({  iterativeCalculation: true,  maxIterations: 100,  maxChange: 0.001,})if (!applied) throw new Error('Could not update calculation settings')console.log(workbook.getCalculationSettings())

建立活頁簿時,也可以透過 createWorkbook() 的 calculationSettings 設定。各活頁簿獨立儲存自己的設定。公式工具列中的「計算選項」提供相同設定。

等待計算結果套用後,可讀取循環參照診斷。getCircularReferences() 不會觸發計算;結果包含工作表 ID、從零開始的列欄座標、循環群組 ID、反覆運算次數,以及可用的收斂資訊。

TypeScript
const formula = univerAPI.getFormula()formula.executeCalculation()await formula.onCalculationResultApplied()console.table(workbook.getCircularReferences())

取得公式字串的計算結果

非同步執行一批公式字串並返回計算結果:

TypeScript
const formulaEngine = univerAPI.getFormula()const formulas = {  Book1: {    Sheet1: {      2: {        3: [          // 完整公式:          '=SUM(A1:A10) + SQRT(D7)',          // 分解後的子公式(每個都可以獨立計算):          'SUM(A1:A10)', // 子公式1          'SQRT(D7)', // 子公式2          'A1:A10', // 範圍參考          'D7', // 單元格參考        ],      },      4: {        5: ['=A2 + B2 + SQRT(C5)', 'A2', 'B2', 'SQRT(C5)'],      },    },  },}const result = await formulaEngine.executeFormulas(formulas)console.log(result)

自訂公式

Univer 支援自訂公式,請參考自訂公式 章節了解如何實作。

常見問題

需要引入 Univer Sheets 的超連結外掛,見超連結模組。

公式值的語意

ISBLANK(A1) 檢查引用儲存格是否有內容,不只是檢查顯示結果是否為空。清空後的儲存格(即使保留格式)為空;傳回 "" 的公式不為空。直接值 ISBLANK("") 也傳回 FALSE。UNIQUE 比較文字時不區分大小寫,保留首次出現的寫法。PROPER 識別 Unicode 字母,包括帶重音的拉丁字母、希臘字母和西里爾字母。AVERAGE 會彙總 FILTER 等函式傳回的完整陣列。

text
=ISBLANK("")                         → FALSE=UNIQUE({"Univer";"univer";"Sheets"})  → {"Univer";"Sheets"}=PROPER("élise müller")               → Élise Müller=AVERAGE({3;7})                      → 5

你覺得這篇文檔如何?

© 2026 DreamNum Co., Ltd.