Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(formula): today function, set numfmt data (#1295)

Dushusirf069dd87ae32
diff --git a/packages/engine-formula/src/basics/__tests__/date.spec.ts b/packages/engine-formula/src/basics/__tests__/date.spec.ts
new file mode 100644
index 0000000000..f2832a4d3a
--- /dev/null
+++ b/packages/engine-formula/src/basics/__tests__/date.spec.ts
@@ -0,0 +1,35 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { excelDateSerial, excelSerialToDate, formatDateDefault } from '../date';
+
+describe('Test date', () => {
+ it('Function excelDateSerial', () => {
+ expect(excelDateSerial(new Date(1900, 1, 28))).toBe(59);
+ expect(excelDateSerial(new Date(1900, 1, 29))).toBe(61);
+ expect(excelDateSerial(new Date(1900, 2, 1))).toBe(61);
+ expect(excelDateSerial(new Date(1901, 0, 1))).toBe(367);
+ expect(excelDateSerial(new Date(2024, 1, 2))).toBe(45324);
+ });
+
+ it('Function excelSerialToDate', () => {
+ expect(formatDateDefault(excelSerialToDate(59))).toBe('1900/02/28');
+ expect(formatDateDefault(excelSerialToDate(61))).toBe('1900/03/01');
+ expect(formatDateDefault(excelSerialToDate(367))).toBe('1901/01/01');
+ expect(formatDateDefault(excelSerialToDate(45324))).toBe('2024/02/02');
+ });
+});
diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.ts
index f15d86765d..8a6121de66 100644
--- a/packages/engine-formula/src/basics/common.ts
+++ b/packages/engine-formula/src/basics/common.ts
@@ -100,6 +100,10 @@ export interface IOtherFormulaData {
[unitId: string]: Nullable<{ [subUnitId: string]: Nullable<{ [formulaId: string]: IFormulaDataItem }> }>;
}
+export interface INumfmtItemMap {
+ [unitId: string]: Nullable<{ [sheetId: string]: IObjectMatrixPrimitiveType<Nullable<string>> }>;
+}
+
/**
* @f formulaString, the text string of the formula.
* @si The formula ID can be utilized in scenarios such as copy-pasting and drag-filling to convert formulas into references, eliminating the need for recreating the formulaString.
@@ -139,6 +143,7 @@ export interface IFormulaDatasetConfig {
dirtyRanges: IUnitRange[];
dirtyNameMap: IDirtyUnitSheetNameMap;
dirtyUnitFeatureMap: IDirtyUnitFeatureMap;
+ numfmtItemMap: INumfmtItemMap;
excludedCell?: IUnitExcludedCell;
allUnitData?: IUnitData;
unitSheetNameMap?: IUnitSheetNameMap;
diff --git a/packages/engine-formula/src/basics/date.ts b/packages/engine-formula/src/basics/date.ts
new file mode 100644
index 0000000000..9a3b3201de
--- /dev/null
+++ b/packages/engine-formula/src/basics/date.ts
@@ -0,0 +1,75 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export const DEFFAULT_DATE_FORMAT = 'yyyy-mm-dd;@';
+
+/**
+ * Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,447 days after January 1, 1900.
+ *
+ * Excel has a leap year error in 1900. February 29, 1900 is considered a legal date. In fact, there is no February 29 in 1900.
+ * 1900.2.28 Date Serial 59
+ * 1900.2.29 Date Serial 61
+ * 1900.3.1 Date Serial 61
+ * 1901.1.1 Date Serial 367
+ * @param date
+ * @returns
+ */
+export function excelDateSerial(date: Date): number {
+ const baseDate = new Date(Date.UTC(1900, 0, 1)); // January 1, 1900, UTC
+ const leapDayDate = new Date(Date.UTC(1900, 1, 28)); // February 28, 1900, UTC
+ const dateInUTC = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate());
+
+ // Calculate the difference in days between the base date and the input date
+ let dayDifference = (dateInUTC - baseDate.getTime()) / (1000 * 3600 * 24);
+
+ // If the date is later than February 28, 1900, the day difference needs to be adjusted to account for Excel errors
+ if (dateInUTC > leapDayDate.getTime()) {
+ dayDifference += 1;
+ }
+
+ return Math.floor(dayDifference) + 1; // Excel serial number starts from 1
+}
+
+export function excelSerialToDate(serial: number): Date {
+ const baseDate = new Date(Date.UTC(1900, 0, 1)); // January 1, 1900, UTC
+ const leapDayDate = new Date(Date.UTC(1900, 1, 28)); // February 28, 1900, UTC
+
+ let dayDifference = Math.floor(serial) - 1; // Adjust for Excel serial number starting from 1
+
+ // If the serial number corresponds to a date later than February 28, 1900, adjust the day difference
+ if (dayDifference > (leapDayDate.getTime() - baseDate.getTime()) / (1000 * 3600 * 24)) {
+ dayDifference -= 1;
+ }
+
+ const resultDate = new Date(baseDate.getTime() + dayDifference * (1000 * 3600 * 24));
+ return resultDate;
+}
+
+export function formatDateDefault(date: Date): string {
+ // Get the year from the date object
+ const year: number = date.getFullYear();
+
+ // Get the month from the date object and add 1 (since getMonth() returns 0-11)
+ // Convert it to a string and pad with zero if necessary to ensure two digits
+ const month: string = (date.getMonth() + 1).toString().padStart(2, '0');
+
+ // Get the day from the date object
+ // Convert it to a string and pad with zero if necessary to ensure two digits
+ const day: string = date.getDate().toString().padStart(2, '0');
+
+ // Concatenate year, month, and day with '/' as separator to form yyyy/mm/dd format
+ return `${year}/${month}/${day}`;
+}
diff --git a/packages/engine-formula/src/basics/object-class-type.ts b/packages/engine-formula/src/basics/object-class-type.ts
index 3dfdaac89b..504538a8fc 100644
--- a/packages/engine-formula/src/basics/object-class-type.ts
+++ b/packages/engine-formula/src/basics/object-class-type.ts
@@ -17,6 +17,16 @@
import { Disposable } from '@univerjs/core';
export class ObjectClassType extends Disposable {
+ pattern: string = '';
+
+ getPattern() {
+ return this.pattern;
+ }
+
+ setPattern(pattern: string) {
+ this.pattern = pattern;
+ }
+
isError() {
return false;
}
diff --git a/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts b/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
index a7643a471b..64bc1021ad 100644
--- a/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
+++ b/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts
@@ -20,6 +20,7 @@ import { CommandType } from '@univerjs/core';
import type {
IDirtyUnitFeatureMap,
IDirtyUnitSheetNameMap,
+ INumfmtItemMap,
IRuntimeOtherUnitDataType,
IRuntimeUnitDataType,
} from '../../basics/common';
@@ -30,6 +31,7 @@ export interface ISetFormulaCalculationStartMutation {
dirtyNameMap: IDirtyUnitSheetNameMap;
dirtyUnitFeatureMap: IDirtyUnitFeatureMap;
options: Nullable<IExecutionOptions>;
+ numfmtItemMap: INumfmtItemMap;
forceCalculation?: boolean;
}
/**
diff --git a/packages/engine-formula/src/commands/mutations/set-numfmt-formula-data.mutation.ts b/packages/engine-formula/src/commands/mutations/set-numfmt-formula-data.mutation.ts
new file mode 100644
index 0000000000..7105cb4657
--- /dev/null
+++ b/packages/engine-formula/src/commands/mutations/set-numfmt-formula-data.mutation.ts
@@ -0,0 +1,36 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IMutation } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
+import type { IAccessor } from '@wendellhu/redi';
+
+import type { INumfmtItemMap } from '../../basics/common';
+import { FormulaDataModel } from '../../models/formula-data.model';
+
+export interface ISetNumfmtFormulaDataMutationParams {
+ numfmtItemMap: INumfmtItemMap;
+}
+
+export const SetNumfmtFormulaDataMutation: IMutation<ISetNumfmtFormulaDataMutationParams> = {
+ id: 'formula.mutation.set-numfmt-formula-data',
+ type: CommandType.MUTATION,
+ handler: (accessor: IAccessor, params: ISetNumfmtFormulaDataMutationParams) => {
+ const formulaDataModel = accessor.get(FormulaDataModel);
+ formulaDataModel.updateNumfmtItemMap(params.numfmtItemMap);
+ return true;
+ },
+};
diff --git a/packages/engine-formula/src/controller/calculate.controller.ts b/packages/engine-formula/src/controller/calculate.controller.ts
index 5b9d3105ba..e680ba1354 100644
--- a/packages/engine-formula/src/controller/calculate.controller.ts
+++ b/packages/engine-formula/src/controller/calculate.controller.ts
@@ -15,10 +15,10 @@
*/
import type { ICommandInfo, IUnitRange } from '@univerjs/core';
-import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle, Tools } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
-import type { IDirtyUnitFeatureMap, IDirtyUnitSheetNameMap, IFormulaData } from '../basics/common';
+import type { IDirtyUnitFeatureMap, IDirtyUnitSheetNameMap, IFormulaData, INumfmtItemMap } from '../basics/common';
import type { ISetArrayFormulaDataMutationParams } from '../commands/mutations/set-array-formula-data.mutation';
import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';
import type { ISetFormulaCalculationStartMutation } from '../commands/mutations/set-formula-calculation.mutation';
@@ -34,6 +34,7 @@ import { FormulaDataModel } from '../models/formula-data.model';
import { CalculateFormulaService } from '../services/calculate-formula.service';
import type { IAllRuntimeData } from '../services/runtime.service';
import { FormulaExecutedStateType } from '../services/runtime.service';
+import { SetNumfmtFormulaDataMutation } from '../commands/mutations/set-numfmt-formula-data.mutation';
@OnLifecycle(LifecycleStages.Ready, CalculateController)
export class CalculateController extends Disposable {
@@ -69,9 +70,9 @@ export class CalculateController extends Disposable {
if (params.forceCalculation === true) {
this._calculate(true);
} else {
- const { dirtyRanges, dirtyNameMap, dirtyUnitFeatureMap } = params;
+ const { dirtyRanges, dirtyNameMap, dirtyUnitFeatureMap, numfmtItemMap } = params;
- this._calculate(false, dirtyRanges, dirtyNameMap, dirtyUnitFeatureMap);
+ this._calculate(false, dirtyRanges, dirtyNameMap, dirtyUnitFeatureMap, numfmtItemMap);
}
} else if (command.id === SetArrayFormulaDataMutation.id) {
const params = command.params as ISetArrayFormulaDataMutationParams;
@@ -92,7 +93,8 @@ export class CalculateController extends Disposable {
forceCalculate: boolean = false,
dirtyRanges: IUnitRange[] = [],
dirtyNameMap: IDirtyUnitSheetNameMap = {},
- dirtyUnitFeatureMap: IDirtyUnitFeatureMap = {}
+ dirtyUnitFeatureMap: IDirtyUnitFeatureMap = {},
+ numfmtItemMap: INumfmtItemMap = {}
) {
if (
dirtyRanges.length === 0 &&
@@ -116,6 +118,7 @@ export class CalculateController extends Disposable {
dirtyRanges,
dirtyNameMap,
dirtyUnitFeatureMap,
+ numfmtItemMap,
});
}
@@ -186,7 +189,7 @@ export class CalculateController extends Disposable {
}
private async _applyFormula(data: IAllRuntimeData) {
- const { unitData, unitOtherData, arrayFormulaRange, arrayFormulaCellData, clearArrayFormulaCellData } = data;
+ const { unitData, unitOtherData, arrayFormulaRange, arrayFormulaCellData, clearArrayFormulaCellData, numfmtItemMap } = data;
if (!unitData) {
console.error('No sheetData from Formula Engine!');
@@ -215,6 +218,19 @@ export class CalculateController extends Disposable {
);
}
+ // Synchronous to the main thread
+ if (!Tools.isEmptyObject(numfmtItemMap)) {
+ this._commandService.executeCommand(
+ SetNumfmtFormulaDataMutation.id,
+ {
+ numfmtItemMap,
+ },
+ {
+ onlyLocal: true,
+ }
+ );
+ }
+
this._commandService.executeCommand(
SetFormulaCalculationResultMutation.id,
{
diff --git a/packages/engine-formula/src/controller/formula.controller.ts b/packages/engine-formula/src/controller/formula.controller.ts
index 94acf29f34..3291cbc3c9 100644
--- a/packages/engine-formula/src/controller/formula.controller.ts
+++ b/packages/engine-formula/src/controller/formula.controller.ts
@@ -58,6 +58,7 @@ import { functionText } from '../functions/text/function-map';
import { functionUniver } from '../functions/univer/function-map';
import { functionWeb } from '../functions/web/function-map';
import { IFunctionService } from '../services/function.service';
+import { SetNumfmtFormulaDataMutation } from '../commands/mutations/set-numfmt-formula-data.mutation';
@OnLifecycle(LifecycleStages.Ready, FormulaController)
export class FormulaController extends Disposable {
@@ -85,6 +86,7 @@ export class FormulaController extends Disposable {
SetFormulaCalculationStopMutation,
SetFormulaCalculationNotificationMutation,
SetFormulaCalculationResultMutation,
+ SetNumfmtFormulaDataMutation,
SetDefinedNameMutation,
RemoveDefinedNameMutation,
diff --git a/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts
index 0fe51ba211..299a16153e 100644
--- a/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts
+++ b/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts
@@ -59,6 +59,7 @@ describe('Test indirect', () => {
formulaData: {},
arrayFormulaCellData: {},
forceCalculate: false,
+ numfmtItemMap: {},
dirtyRanges: [],
dirtyNameMap: {},
dirtyUnitFeatureMap: {},
diff --git a/packages/engine-formula/src/engine/ast-node/reference-node.ts b/packages/engine-formula/src/engine/ast-node/reference-node.ts
index 1313957492..3ba75b86dd 100644
--- a/packages/engine-formula/src/engine/ast-node/reference-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/reference-node.ts
@@ -71,6 +71,8 @@ export class ReferenceNode extends BaseAstNode {
this._referenceObject.setRuntimeData(runtimeService.getUnitData());
+ this._referenceObject.setNumfmtItemData(currentConfigService.getNumfmtItemMap());
+
this._referenceObject.setRuntimeArrayFormulaCellData(runtimeService.getRuntimeArrayFormulaCellData());
this._referenceObject.setRuntimeFeatureCellData(runtimeService.getRuntimeFeatureCellData());
diff --git a/packages/engine-formula/src/engine/ast-node/suffix-node.ts b/packages/engine-formula/src/engine/ast-node/suffix-node.ts
index c3cb14d3bd..2a5f047ecd 100644
--- a/packages/engine-formula/src/engine/ast-node/suffix-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/suffix-node.ts
@@ -63,6 +63,9 @@ export class SuffixNode extends BaseAstNode {
value as BaseValueObject,
new NumberValueObject(100)
) as FunctionVariantType;
+
+ // set number format
+ result.setPattern('0.00%');
} else if (this._operatorString === suffixToken.POUND) {
result = this._handlerPound(value);
} else {
diff --git a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts b/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
index 9cceaf27ca..efa9f0ca81 100644
--- a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
+++ b/packages/engine-formula/src/engine/reference-object/base-reference-object.ts
@@ -18,7 +18,7 @@ import type { ICellData, IRange, Nullable } from '@univerjs/core';
import { CellValueType, isNullCell } from '@univerjs/core';
import { FormulaAstLRU } from '../../basics/cache-lru';
-import type { IRuntimeUnitDataType, IUnitData, IUnitSheetNameMap } from '../../basics/common';
+import type { INumfmtItemMap, IRuntimeUnitDataType, IUnitData, IUnitSheetNameMap } from '../../basics/common';
import { ERROR_TYPE_SET, ErrorType } from '../../basics/error-type';
import { ObjectClassType } from '../../basics/object-class-type';
import { ArrayValueObject, ValueObjectFactory } from '../value-object/array-value-object';
@@ -66,6 +66,8 @@ export class BaseReferenceObject extends ObjectClassType {
private _runtimeFeatureCellData: { [featureId: string]: IRuntimeUnitDataType } = {};
+ private _numfmtItemData: INumfmtItemMap = {};
+
private _refOffsetX = 0;
private _refOffsetY = 0;
@@ -144,6 +146,9 @@ export class BaseReferenceObject extends ObjectClassType {
return callback(new ErrorValueObject(ErrorType.VALUE), startRow, startColumn);
}
+ const unitId = this._forcedUnitId || this._defaultUnitId;
+ const sheetId = this._forcedSheetId || this._defaultSheetId;
+
for (let r = startRow; r <= endRow; r++) {
for (let c = startColumn; c <= endColumn; c++) {
if (r < 0 || c < 0) {
@@ -159,6 +164,9 @@ export class BaseReferenceObject extends ObjectClassType {
const resultObjectValue = this.getCellValueObject(cell);
+ const pattern = this._numfmtItemData[unitId]?.[sheetId]?.[r]?.[c];
+ pattern && resultObjectValue.setPattern(pattern);
+
result = callback(resultObjectValue, r, c);
if (result === false) {
@@ -176,7 +184,15 @@ export class BaseReferenceObject extends ObjectClassType {
return new NumberValueObject(0, true);
}
- return this.getCellValueObject(cell);
+ const cellValueObject = this.getCellValueObject(cell);
+
+ // Set numfmt pattern
+ const unitId = this._forcedUnitId || this._defaultUnitId;
+ const sheetId = this._forcedSheetId || this._defaultSheetId;
+ const numfmtItem = this._numfmtItemData[unitId]?.[sheetId]?.[startRow]?.[startColumn];
+ numfmtItem && cellValueObject.setPattern(numfmtItem);
+
+ return cellValueObject;
}
getRangeData() {
@@ -289,6 +305,14 @@ export class BaseReferenceObject extends ObjectClassType {
this._runtimeFeatureCellData = unitData;
}
+ getNumfmtItemData() {
+ return this._numfmtItemData;
+ }
+
+ setNumfmtItemData(numfmtItemData: INumfmtItemMap) {
+ this._numfmtItemData = numfmtItemData;
+ }
+
getRowCount() {
return this.getCurrentActiveSheetData().rowCount;
}
diff --git a/packages/engine-formula/src/engine/reference-object/cell-reference-object.ts b/packages/engine-formula/src/engine/reference-object/cell-reference-object.ts
index 7613562a10..47d4cbe58a 100644
--- a/packages/engine-formula/src/engine/reference-object/cell-reference-object.ts
+++ b/packages/engine-formula/src/engine/reference-object/cell-reference-object.ts
@@ -96,6 +96,8 @@ export class CellReferenceObject extends BaseReferenceObject {
rangeReferenceObject.setRuntimeData(this.getRuntimeData());
+ rangeReferenceObject.setNumfmtItemData(this.getNumfmtItemData());
+
rangeReferenceObject.setArrayFormulaCellData(this.getArrayFormulaCellData());
rangeReferenceObject.setRuntimeArrayFormulaCellData(this.getRuntimeArrayFormulaCellData());
diff --git a/packages/engine-formula/src/engine/value-object/primitive-object.ts b/packages/engine-formula/src/engine/value-object/primitive-object.ts
index 4f23fc3340..33596894a0 100644
--- a/packages/engine-formula/src/engine/value-object/primitive-object.ts
+++ b/packages/engine-formula/src/engine/value-object/primitive-object.ts
@@ -102,47 +102,47 @@ export class NullValueObject extends BaseValueObject {
}
override sqrt(): BaseValueObject {
- return new NumberValueObject(0, true);
+ return new NumberValueObject(0, true).sqrt();
}
override cbrt(): BaseValueObject {
- return new NumberValueObject(0, true);
+ return new NumberValueObject(0, true).cbrt();
}
override cos(): BaseValueObject {
- return new NumberValueObject(0, true);
+ return new NumberValueObject(0, true).cos();
}
override acos(): BaseValueObject {
- return new NumberValueObject(0, true);
+ return new NumberValueObject(0, true).acos();
}
override acosh(): BaseValueObject {
- return new NumberValueObject(0, true);
+ return new NumberValueObject(0, true).acosh();
}
override sin(): BaseValueObject {
- return new NumberValueObject(0, true);
+ return new NumberValueObject(0, true).sin();
}
override asin(): BaseValueObject {
- return new NumberValueObject(0, true);
+ return new NumberValueObject(0, true).asin();
}
override asinh(): BaseValueObject {
- return new NumberValueObject(0, true);
+ return new NumberValueObject(0, true).asinh();
}
override tan(): BaseValueObject {
- return new NumberValueObject(0, true);
+ return new NumberValueObject(0, true).tan();
}
override tanh(): BaseValueObject {
- return new NumberValueObject(0, true);
+ return new NumberValueObject(0, true).tanh();
}
override atan(): BaseValueObject {
- return new NumberValueObject(0, true);
+ return new NumberValueObject(0, true).atan();
}
override atan2(valueObject: BaseValueObject): BaseValueObject {
@@ -150,7 +150,7 @@ export class NullValueObject extends BaseValueObject {
}
override atanh(): BaseValueObject {
- return new NumberValueObject(0, true);
+ return new NumberValueObject(0, true).atanh();
}
override log(): BaseValueObject {
@@ -162,11 +162,11 @@ export class NullValueObject extends BaseValueObject {
}
override exp(): BaseValueObject {
- return new ErrorValueObject(ErrorType.NUM);
+ return new NumberValueObject(0, true).exp();
}
override abs(): BaseValueObject {
- return new ErrorValueObject(ErrorType.NUM);
+ return new NumberValueObject(0, true).abs();
}
override round(valueObject: BaseValueObject): BaseValueObject {
@@ -400,6 +400,9 @@ export class NumberValueObject extends BaseValueObject {
return object;
}
+ // Set number format
+ object.setPattern(this.getPattern() || valueObject.getPattern());
+
return object;
}
@@ -420,6 +423,9 @@ export class NumberValueObject extends BaseValueObject {
return this;
}
+ // Set number format
+ object.setPattern(this.getPattern() || valueObject.getPattern());
+
return object;
}
@@ -427,7 +433,12 @@ export class NumberValueObject extends BaseValueObject {
if (valueObject.isArray()) {
return valueObject.multiply(this);
}
- return this.multiplyBy(valueObject.getValue());
+ const object = this.multiplyBy(valueObject.getValue());
+
+ // Set number format
+ object.setPattern(this.getPattern() || valueObject.getPattern());
+
+ return object;
}
override divided(valueObject: BaseValueObject): BaseValueObject {
@@ -438,7 +449,12 @@ export class NumberValueObject extends BaseValueObject {
}
return (o as BaseValueObject).multiply(this);
}
- return this.dividedBy(valueObject.getValue());
+ const object = this.dividedBy(valueObject.getValue());
+
+ // Set number format
+ object.setPattern(this.getPattern() || valueObject.getPattern());
+
+ return object;
}
override concatenateFront(valueObject: BaseValueObject): BaseValueObject {
diff --git a/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts b/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts
index 03988d67b4..3d8e9ad513 100644
--- a/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts
+++ b/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts
@@ -54,92 +54,94 @@ import { IOtherFormulaManagerService, OtherFormulaManagerService } from '../../s
import { FormulaRuntimeService, IFormulaRuntimeService } from '../../services/runtime.service';
import { ISuperTableService, SuperTableService } from '../../services/super-table.service';
-const TEST_WORKBOOK_DATA: IWorkbookData = {
- id: 'test',
- appVersion: '3.0.0-alpha',
- sheets: {
- sheet1: {
- id: 'sheet1',
- cellData: {
- 0: {
- 0: {
- v: 1,
- t: CellValueType.NUMBER,
- },
- 1: {
- v: 2,
- t: CellValueType.NUMBER,
- },
- },
- 1: {
- 0: {
- v: 3,
- t: CellValueType.NUMBER,
- },
- 1: {
- v: 4,
- t: CellValueType.NUMBER,
- },
- 2: {
- v: 'B2',
- t: CellValueType.STRING,
- },
- 3: {
- v: 'R2C2',
- t: CellValueType.STRING,
- },
- },
- 2: {
- 0: {
- v: 1,
- t: CellValueType.NUMBER,
- },
- 1: {
- v: ' ',
- t: CellValueType.STRING,
- },
- 2: {
- v: 1.23,
- t: CellValueType.NUMBER,
- },
- 3: {
- v: true,
- t: CellValueType.BOOLEAN,
- },
- 4: {
- v: false,
- t: CellValueType.BOOLEAN,
- },
- },
- 3: {
+const getTestWorkbookData = (): IWorkbookData => {
+ return {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: {
0: {
- v: 0,
- t: CellValueType.NUMBER,
+ 0: {
+ v: 1,
+ t: CellValueType.NUMBER,
+ },
+ 1: {
+ v: 2,
+ t: CellValueType.NUMBER,
+ },
},
1: {
- v: '100',
- t: CellValueType.STRING,
+ 0: {
+ v: 3,
+ t: CellValueType.NUMBER,
+ },
+ 1: {
+ v: 4,
+ t: CellValueType.NUMBER,
+ },
+ 2: {
+ v: 'B2',
+ t: CellValueType.STRING,
+ },
+ 3: {
+ v: 'R2C2',
+ t: CellValueType.STRING,
+ },
},
2: {
- v: '2.34',
- t: CellValueType.STRING,
+ 0: {
+ v: 1,
+ t: CellValueType.NUMBER,
+ },
+ 1: {
+ v: ' ',
+ t: CellValueType.STRING,
+ },
+ 2: {
+ v: 1.23,
+ t: CellValueType.NUMBER,
+ },
+ 3: {
+ v: true,
+ t: CellValueType.BOOLEAN,
+ },
+ 4: {
+ v: false,
+ t: CellValueType.BOOLEAN,
+ },
},
3: {
- v: 'test',
- t: CellValueType.STRING,
- },
- 4: {
- v: -3,
- t: CellValueType.NUMBER,
+ 0: {
+ v: 0,
+ t: CellValueType.NUMBER,
+ },
+ 1: {
+ v: '100',
+ t: CellValueType.STRING,
+ },
+ 2: {
+ v: '2.34',
+ t: CellValueType.STRING,
+ },
+ 3: {
+ v: 'test',
+ t: CellValueType.STRING,
+ },
+ 4: {
+ v: -3,
+ t: CellValueType.NUMBER,
+ },
},
},
},
},
- },
- locale: LocaleType.ZH_CN,
- name: '',
- sheetOrder: [],
- styles: {},
+ locale: LocaleType.ZH_CN,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+ };
};
export function createFunctionTestBed(workbookConfig?: IWorkbookData, dependencies?: Dependency[]) {
const univer = new Univer();
@@ -204,7 +206,7 @@ export function createFunctionTestBed(workbookConfig?: IWorkbookData, dependenci
}
univer.registerPlugin(TestSpyPlugin);
- const sheet = univer.createUniverSheet(workbookConfig || TEST_WORKBOOK_DATA);
+ const sheet = univer.createUniverSheet(workbookConfig || getTestWorkbookData());
if (get === undefined) {
throw new Error('[TestPlugin]: not hooked on!');
diff --git a/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts b/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts
new file mode 100644
index 0000000000..f2ccf25493
--- /dev/null
+++ b/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts
@@ -0,0 +1,327 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Injector } from '@wendellhu/redi';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import type { IWorkbookData } from '@univerjs/core';
+import { LocaleType } from '@univerjs/core';
+import type { ArrayValueObject, BaseValueObject, LexerNode } from '../..';
+import { FUNCTION_NAMES_DATE, FUNCTION_NAMES_LOGICAL, FUNCTION_NAMES_LOOKUP, FUNCTION_NAMES_MATH, FUNCTION_NAMES_STATISTICAL, FUNCTION_NAMES_TEXT, IFunctionService } from '../..';
+import { Lexer } from '../../engine/analysis/lexer';
+import { AstTreeBuilder } from '../../engine/analysis/parser';
+import type { BaseAstNode } from '../../engine/ast-node/base-ast-node';
+import { Interpreter } from '../../engine/interpreter/interpreter';
+import { Iferror } from '../logical/iferror';
+import { Xlookup } from '../lookup/xlookup';
+import { Max } from '../statistical/max';
+import { Sumifs } from '../math/sumifs';
+import { Edate } from '../date/edate';
+import { Today } from '../date/today';
+import { Day } from '../date/day';
+import { Address } from '../lookup/address';
+import { Xmatch } from '../lookup/xmatch';
+import { Min } from '../statistical/min';
+import { IFormulaCurrentConfigService } from '../../services/current-data.service';
+import { IFormulaRuntimeService } from '../../services/runtime.service';
+import { Plus } from '../meta/plus';
+import { FUNCTION_NAMES_META } from '../meta/function-names';
+import { Minus } from '../meta/minus';
+import { Concatenate } from '../text/concatenate';
+import { createFunctionTestBed } from './create-function-test-bed';
+
+const getFunctionsTestWorkbookData = (): IWorkbookData => {
+ return {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: {
+ 0: {
+ 0: {
+ v: 'A',
+ t: 1,
+ },
+ 1: {
+ v: 'B',
+ t: 1,
+ },
+ 2: {
+ v: 'C',
+ t: 1,
+ },
+ 3: {
+ v: 'D',
+ t: 1,
+ },
+ },
+ 1: {
+ 0: {
+ v: 44927,
+ t: 2,
+ },
+ 1: {
+ v: 101,
+ t: 2,
+ },
+ 2: {
+ v: 5,
+ t: 2,
+ },
+ 3: {
+ v: 500,
+ t: 2,
+ },
+ },
+ 2: {
+ 0: {
+ v: 44928,
+ t: 2,
+ },
+ 1: {
+ v: 102,
+ t: 2,
+ },
+ 2: {
+ v: 3,
+ t: 2,
+ },
+ 3: {
+ v: 300,
+ t: 2,
+ },
+ },
+ 3: {
+ 0: {
+ v: 44929,
+ t: 2,
+ },
+ 1: {
+ v: 103,
+ t: 2,
+ },
+ 2: {
+ v: 2,
+ t: 2,
+ },
+ 3: {
+ v: 200,
+ t: 2,
+ },
+ },
+ 4: {
+ 0: {
+ v: 44930,
+ t: 2,
+ },
+ 1: {
+ v: 104,
+ t: 2,
+ },
+ 2: {
+ v: 4,
+ t: 2,
+ },
+ 3: {
+ v: 400,
+ t: 2,
+ },
+ },
+ 5: {
+ 0: {
+ v: 44931,
+ t: 2,
+ },
+ 1: {
+ v: 105,
+ t: 2,
+ },
+ 2: {
+ v: 1,
+ t: 2,
+ },
+ 3: {
+ v: 100,
+ t: 2,
+ },
+ },
+ 6: {
+ 0: {
+ v: 44932,
+ t: 2,
+ },
+ 1: {
+ v: 101,
+ t: 2,
+ },
+ 2: {
+ v: 3,
+ t: 2,
+ },
+ 3: {
+ v: 300,
+ t: 2,
+ },
+ },
+ 7: {
+ 0: {
+ v: 44933,
+ t: 2,
+ },
+ 1: {
+ v: 102,
+ t: 2,
+ },
+ 2: {
+ v: 4,
+ t: 2,
+ },
+ 3: {
+ v: 400,
+ t: 2,
+ },
+ },
+ 8: {
+ 0: {
+ v: 44934,
+ t: 2,
+ },
+ 1: {
+ v: 103,
+ t: 2,
+ },
+ 2: {
+ v: 5,
+ t: 2,
+ },
+ 3: {
+ v: 500,
+ t: 2,
+ },
+ },
+ 9: {
+ 0: {
+ v: 44935,
+ t: 2,
+ },
+ 1: {
+ v: 104,
+ t: 2,
+ },
+ 2: {
+ v: 2,
+ t: 2,
+ },
+ 3: {
+ v: 200,
+ t: 2,
+ },
+ },
+ },
+ },
+ },
+ locale: LocaleType.ZH_CN,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+ };
+};
+describe('Test nested functions', () => {
+ let get: Injector['get'];
+ let lexer: Lexer;
+ let astTreeBuilder: AstTreeBuilder;
+ let interpreter: Interpreter;
+
+ beforeEach(() => {
+ const testBed = createFunctionTestBed(getFunctionsTestWorkbookData());
+
+ get = testBed.get;
+
+ lexer = get(Lexer);
+ astTreeBuilder = get(AstTreeBuilder);
+ interpreter = get(Interpreter);
+
+ const functionService = get(IFunctionService);
+
+ const formulaCurrentConfigService = get(IFormulaCurrentConfigService);
+
+ const formulaRuntimeService = get(IFormulaRuntimeService);
+
+ formulaCurrentConfigService.load({
+ formulaData: {},
+ arrayFormulaCellData: {},
+ forceCalculate: false,
+ numfmtItemMap: {},
+ dirtyRanges: [],
+ dirtyNameMap: {},
+ dirtyUnitFeatureMap: {},
+ excludedCell: {},
+ allUnitData: {
+ [testBed.unitId]: testBed.sheetData,
+ },
+ });
+
+ const sheetItem = testBed.sheetData[testBed.sheetId];
+
+ formulaRuntimeService.setCurrent(
+ 0,
+ 0,
+ sheetItem.rowCount,
+ sheetItem.columnCount,
+ testBed.sheetId,
+ testBed.unitId
+ );
+
+ functionService.registerExecutors(
+ new Iferror(FUNCTION_NAMES_LOGICAL.IFERROR),
+ new Xlookup(FUNCTION_NAMES_LOOKUP.XLOOKUP),
+ new Max(FUNCTION_NAMES_STATISTICAL.MAX),
+ new Sumifs(FUNCTION_NAMES_MATH.SUMIFS),
+ new Edate(FUNCTION_NAMES_DATE.EDATE),
+ new Today(FUNCTION_NAMES_DATE.TODAY),
+ new Day(FUNCTION_NAMES_DATE.DAY),
+ new Address(FUNCTION_NAMES_LOOKUP.ADDRESS),
+ new Xmatch(FUNCTION_NAMES_LOOKUP.XMATCH),
+ new Min(FUNCTION_NAMES_STATISTICAL.MIN),
+ new Plus(FUNCTION_NAMES_META.PLUS),
+ new Minus(FUNCTION_NAMES_META.MINUS),
+ new Concatenate(FUNCTION_NAMES_TEXT.CONCATENATE)
+
+ );
+ });
+
+ describe('Normal', () => {
+ it('Nested functions IFERROR,XLOOKUP,MAX,SUMIFS,EDATE,TODAY,DAY,PLUS,Minus,CONCATENATE', async () => {
+ const lexerNode = lexer.treeBuilder('=IFERROR(XLOOKUP(MAX(SUMIFS(C2:C10, A2:A10, ">="&EDATE(TODAY(),-1)+1-DAY(TODAY()), A2:A10, "<"&TODAY()-DAY(TODAY())+1)), SUMIFS(C2:C10, A2:A10, ">="&EDATE(TODAY(),-1)+1-DAY(TODAY()), A2:A10, "<"&TODAY()-DAY(TODAY())+1), B2:B10, "No Data"), "No Data")');
+
+ const astNode = astTreeBuilder.parse(lexerNode as LexerNode);
+
+ const result = await interpreter.executeAsync(astNode as BaseAstNode);
+
+ expect((result as ArrayValueObject).toValue()).toStrictEqual([[101], [102], [103], [104], [105], [101], [102], [103], [104]]);
+ });
+ it('Nested functions ADDRESS,XMATCH,MIN,SUMIFS,EDATE,TODAY,DAY', async () => {
+ const lexerNode = lexer.treeBuilder('=ADDRESS(XMATCH(MIN(SUMIFS(C2:C10, A2:A10, ">=" & EDATE(TODAY(), -1) + 1 - DAY(TODAY()), A2:A10, "<" & TODAY() - DAY(TODAY()) + 1)), SUMIFS(C2:C10, A2:A10, ">=" & EDATE(TODAY(), -1) + 1 - DAY(TODAY()), A2:A10, "<" & TODAY() - DAY(TODAY()) + 1), 0) + 1, 2)');
+
+ const astNode = astTreeBuilder.parse(lexerNode as LexerNode);
+
+ const result = await interpreter.executeAsync(astNode as BaseAstNode);
+
+ expect((result as BaseValueObject).getValue()).toBe('$B$2');
+ });
+ });
+});
diff --git a/packages/engine-formula/src/functions/base-function.ts b/packages/engine-formula/src/functions/base-function.ts
index ebede88dfc..b62745b4dc 100644
--- a/packages/engine-formula/src/functions/base-function.ts
+++ b/packages/engine-formula/src/functions/base-function.ts
@@ -165,6 +165,40 @@ export class BaseFunction extends Disposable {
return logicValue;
}
+ /**
+ * A logical value that specifies 1/TRUE , 0/FALSE, -1, default 1.
+ * The difference from getZeroOrOneByOneDefault is that we need to get -1
+ * @param logicValueObject
+ * @returns
+ */
+ getMatchTypeValue(logicValueObject?: BaseValueObject) {
+ if (logicValueObject == null) {
+ return 1;
+ }
+
+ let logicValue = 1;
+
+ if (logicValueObject.isArray()) {
+ logicValueObject = (logicValueObject as ArrayValueObject).getFirstCell();
+ }
+
+ if (logicValueObject.isBoolean()) {
+ const logicV = logicValueObject.getValue() as boolean;
+ if (logicV === false) {
+ logicValue = 0;
+ }
+ } else if (logicValueObject.isString()) {
+ return;
+ } else if (logicValueObject.isNumber()) {
+ const logicV = logicValueObject.getValue() as number;
+ if (logicV <= 0) {
+ logicValue = logicV;
+ }
+ }
+
+ return logicValue;
+ }
+
binarySearch(
value: BaseValueObject,
searchArray: ArrayValueObject,
diff --git a/packages/engine-formula/src/functions/date/date/__tests__/index.spec.ts b/packages/engine-formula/src/functions/date/date/__tests__/index.spec.ts
new file mode 100644
index 0000000000..ede45fc13e
--- /dev/null
+++ b/packages/engine-formula/src/functions/date/date/__tests__/index.spec.ts
@@ -0,0 +1,139 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import { FUNCTION_NAMES_DATE } from '../../function-names';
+import { DateFunction } from '..';
+import { NumberValueObject } from '../../../../engine/value-object/primitive-object';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
+import { ErrorType } from '../../../..';
+
+describe('Test date function', () => {
+ const textFunction = new DateFunction(FUNCTION_NAMES_DATE.DATE);
+
+ describe('Date', () => {
+ it('All value is normal', () => {
+ const year = new NumberValueObject(2024);
+ const month = new NumberValueObject(1);
+ const day = new NumberValueObject(1);
+ const result = textFunction.calculate(year, month, day);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[45292]]);
+ });
+ it('Edge case, 1900.1.1', () => {
+ const year = new NumberValueObject(1900);
+ const month = new NumberValueObject(1);
+ const day = new NumberValueObject(1);
+ const result = textFunction.calculate(year, month, day);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[1]]);
+ });
+ it('Edge case, 1900.1.0', () => {
+ const year = new NumberValueObject(1900);
+ const month = new NumberValueObject(1);
+ const day = new NumberValueObject(0);
+ const result = textFunction.calculate(year, month, day);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[0]]);
+ });
+ it('Edge case, 1900.1.-1', () => {
+ const year = new NumberValueObject(1900);
+ const month = new NumberValueObject(1);
+ const day = new NumberValueObject(-1);
+ const result = textFunction.calculate(year, month, day);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[ErrorType.NUM]]);
+ });
+
+ it('Year is single cell, month is one column, day is one row', () => {
+ const year = new NumberValueObject(2024);
+ const month = new ArrayValueObject({
+ calculateValueList: transformToValueObject([[1], [2]]),
+ rowCount: 2,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const day = new ArrayValueObject({
+ calculateValueList: transformToValueObject([[3, 4, 5]]),
+ rowCount: 1,
+ columnCount: 3,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const result = textFunction.calculate(year, month, day);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[45294, 45295, 45296], [45325, 45326, 45327]]);
+ });
+
+ it('Year is array with multiple format values', () => {
+ const year = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [1, ' ', 1.23, true, false, null, 18],
+ [0, '100', '2.34', 'test', -3, 1900, 108],
+ ]),
+ rowCount: 2,
+ columnCount: 7,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const month = new NumberValueObject(1);
+ const day = new NumberValueObject(1);
+ const result = textFunction.calculate(year, month, day);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[367, '#VALUE!', 367, 367, 1, 1, 6576], [1, 36526, 732, '#VALUE!', '#NUM!', 1, 39448]]);
+ });
+
+ it('Month is array with multiple format values', () => {
+ const year = new NumberValueObject(2024);
+ const month = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [1, ' ', 1.23, true, false, null],
+ [0, '100', '2.34', 'test', -3, 14],
+ ]),
+ rowCount: 2,
+ columnCount: 6,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const day = new NumberValueObject(1);
+ const result = textFunction.calculate(year, month, day);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[45292, '#VALUE!', 45292, 45292, 45261, 45261], [45261, 48305, 45323, '#VALUE!', 45170, 45689]]);
+ });
+
+ it('Day is array with multiple format values', () => {
+ const year = new NumberValueObject(2024);
+ const month = new NumberValueObject(1);
+ const day = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [1, ' ', 1.23, true, false, null],
+ [0, '100', '2.34', 'test', -3, 32],
+ ]),
+ rowCount: 2,
+ columnCount: 6,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const result = textFunction.calculate(year, month, day);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[45292, '#VALUE!', 45292, 45292, 45291, 45291], [45291, 45391, 45293, '#VALUE!', 45288, 45323]]);
+ });
+ });
+});
diff --git a/packages/engine-formula/src/functions/date/date/index.ts b/packages/engine-formula/src/functions/date/date/index.ts
new file mode 100644
index 0000000000..23333c5364
--- /dev/null
+++ b/packages/engine-formula/src/functions/date/date/index.ts
@@ -0,0 +1,108 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DEFFAULT_DATE_FORMAT, excelDateSerial } from '../../../basics/date';
+import { ErrorType } from '../../../basics/error-type';
+import { expandArrayValueObject } from '../../../engine/utils/array-object';
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
+import { NumberValueObject } from '../../../engine/value-object/primitive-object';
+import { BaseFunction } from '../../base-function';
+
+export class DateFunction extends BaseFunction {
+ override calculate(year: BaseValueObject, month: BaseValueObject, day: BaseValueObject) {
+ if (year == null || month == null || day == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (year.isError()) {
+ return year;
+ }
+
+ if (month.isError()) {
+ return month;
+ }
+
+ if (day.isError()) {
+ return day;
+ }
+
+ // get max row length
+ const maxRowLength = Math.max(
+ year.isArray() ? (year as ArrayValueObject).getRowCount() : 1,
+ month.isArray() ? (month as ArrayValueObject).getRowCount() : 1,
+ day.isArray() ? (day as ArrayValueObject).getRowCount() : 1
+ );
+
+ // get max column length
+ const maxColumnLength = Math.max(
+ year.isArray() ? (year as ArrayValueObject).getColumnCount() : 1,
+ month.isArray() ? (month as ArrayValueObject).getColumnCount() : 1,
+ day.isArray() ? (day as ArrayValueObject).getColumnCount() : 1
+ );
+
+ const yearArray = expandArrayValueObject(maxRowLength, maxColumnLength, year);
+ const monthArray = expandArrayValueObject(maxRowLength, maxColumnLength, month);
+ const dayArray = expandArrayValueObject(maxRowLength, maxColumnLength, day);
+
+ return yearArray.map((yearValueObject, rowIndex, columnIndex) => {
+ const monthValueObject = monthArray.get(rowIndex, columnIndex);
+ const dayValueObject = dayArray.get(rowIndex, columnIndex);
+
+ if (yearValueObject.isError()) {
+ return yearValueObject;
+ }
+
+ if (monthValueObject.isError()) {
+ return monthValueObject;
+ }
+
+ if (dayValueObject.isError()) {
+ return dayValueObject;
+ }
+
+ if (yearValueObject.isString() || monthValueObject.isString() || dayValueObject.isString()) {
+ return new ErrorValueObject(ErrorType.VALUE);
+ }
+
+ let yearValue = +yearValueObject.getValue();
+ const monthValue = Math.floor(+monthValueObject.getValue());
+ const dayValue = +dayValueObject.getValue();
+
+ if (yearValue < 0 || yearValue > 9999) {
+ return new ErrorValueObject(ErrorType.NUM);
+ }
+
+ if (yearValue >= 0 && yearValue < 1899) {
+ yearValue += 1900;
+ }
+
+ const date = new Date(yearValue, monthValue - 1, dayValue);
+
+ const currentSerial = excelDateSerial(date);
+
+ if (currentSerial < 0) {
+ return new ErrorValueObject(ErrorType.NUM);
+ }
+
+ const valueObject = new NumberValueObject(currentSerial);
+ valueObject.setPattern(DEFFAULT_DATE_FORMAT);
+
+ return valueObject;
+ });
+ }
+}
diff --git a/packages/engine-formula/src/functions/date/day/__tests__/index.spec.ts b/packages/engine-formula/src/functions/date/day/__tests__/index.spec.ts
new file mode 100644
index 0000000000..35f966ef85
--- /dev/null
+++ b/packages/engine-formula/src/functions/date/day/__tests__/index.spec.ts
@@ -0,0 +1,49 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import { FUNCTION_NAMES_DATE } from '../../function-names';
+import { Day } from '..';
+import { NumberValueObject } from '../../../../engine/value-object/primitive-object';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
+
+describe('Test day function', () => {
+ const textFunction = new Day(FUNCTION_NAMES_DATE.DAY);
+
+ describe('Day', () => {
+ it('Serial number is normal', () => {
+ const serialNumber = new NumberValueObject(43831);
+ const result = textFunction.calculate(serialNumber);
+ expect(result.getValue()).toStrictEqual(1);
+ });
+
+ it('Serial number is array', () => {
+ const serialNumber = new ArrayValueObject({
+ calculateValueList: transformToValueObject([[1, ' ', 1.23, true, false, null],
+ [0, '100', '2.34', 'test', -3, 1900]]),
+ rowCount: 2,
+ columnCount: 6,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const result = textFunction.calculate(serialNumber);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[1, '#VALUE!', 1, 1, 0, '#VALUE!'], [0, 9, 2, '#VALUE!', '#NUM!', 14]]);
+ });
+ });
+});
diff --git a/packages/engine-formula/src/functions/date/day/index.ts b/packages/engine-formula/src/functions/date/day/index.ts
new file mode 100644
index 0000000000..999913a041
--- /dev/null
+++ b/packages/engine-formula/src/functions/date/day/index.ts
@@ -0,0 +1,67 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { excelSerialToDate } from '../../../basics/date';
+import { ErrorType } from '../../../basics/error-type';
+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
+import { NumberValueObject } from '../../../engine/value-object/primitive-object';
+import { BaseFunction } from '../../base-function';
+
+export class Day extends BaseFunction {
+ override calculate(serialNumber: BaseValueObject) {
+ if (serialNumber == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (serialNumber.isError()) {
+ return serialNumber;
+ }
+
+ if (serialNumber.isArray()) {
+ return serialNumber.map((serialNumberObject) => {
+ if (serialNumberObject.isError()) {
+ return serialNumberObject;
+ }
+
+ if (serialNumberObject.isString() || serialNumberObject.isNull()) {
+ return new ErrorValueObject(ErrorType.VALUE);
+ }
+
+ const dateSerial = +serialNumberObject.getValue();
+
+ if (dateSerial < 0) {
+ return new ErrorValueObject(ErrorType.NUM);
+ }
+
+ // Excel serial 0 is 1900-01-00
+ // Google Sheets serial 0 is 1899-12-30
+ if (dateSerial === 0) {
+ return new NumberValueObject(0);
+ }
+
+ const date = excelSerialToDate(dateSerial);
+
+ const month = date.getDate();
+ const valueObject = new NumberValueObject(month);
+
+ return valueObject;
+ });
+ }
+
+ return new NumberValueObject(excelSerialToDate(+serialNumber.getValue()).getDate());
+ }
+}
diff --git a/packages/engine-formula/src/functions/date/edate/__tests__/index.spec.ts b/packages/engine-formula/src/functions/date/edate/__tests__/index.spec.ts
new file mode 100644
index 0000000000..6f794784b7
--- /dev/null
+++ b/packages/engine-formula/src/functions/date/edate/__tests__/index.spec.ts
@@ -0,0 +1,99 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import { FUNCTION_NAMES_DATE } from '../../function-names';
+import { Edate } from '..';
+import { NumberValueObject } from '../../../../engine/value-object/primitive-object';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
+
+describe('Test edate function', () => {
+ const textFunction = new Edate(FUNCTION_NAMES_DATE.EDATE);
+
+ describe('Edate', () => {
+ it('All value is normal', () => {
+ const startDate = new NumberValueObject(43831);
+ const months = new NumberValueObject(1);
+ const result = textFunction.calculate(startDate, months);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[43862]]);
+ });
+
+ it('Start date is array', () => {
+ const startDate = new ArrayValueObject({
+ calculateValueList: transformToValueObject([[43832], [43833]]),
+ rowCount: 2,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const months = new NumberValueObject(1);
+ const result = textFunction.calculate(startDate, months);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[43863], [43864]]);
+ });
+
+ it('Start date is array with multiple format values', () => {
+ const startDate = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [1, ' ', 1.23, true, false, null],
+ [0, '100', '2.34', 'test', -3, 1900],
+ ]),
+ rowCount: 2,
+ columnCount: 6,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const months = new NumberValueObject(1);
+ const result = textFunction.calculate(startDate, months);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[32, '#VALUE!', 32, '#VALUE!', '#VALUE!', 31], [31, 130, 33, '#VALUE!', '#NUM!', 1931]]);
+ });
+
+ it('Months is array', () => {
+ const startDate = new NumberValueObject(43831);
+ const months = new ArrayValueObject({
+ calculateValueList: transformToValueObject([[1], [2]]),
+ rowCount: 2,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const result = textFunction.calculate(startDate, months);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[43862], [43891]]);
+ });
+
+ it('Months is array with multiple format values', () => {
+ const startDate = new NumberValueObject(43831);
+ const months = new ArrayValueObject({
+ calculateValueList: transformToValueObject([[1, ' ', 1.23, true, false, null],
+ [0, '100', '2.34', 'test', -3, 1900]]),
+ rowCount: 2,
+ columnCount: 6,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const result = textFunction.calculate(startDate, months);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[43862, '#VALUE!', 43862, '#VALUE!', '#VALUE!', 43831], [43831, 46874, 43891, '#VALUE!', 43739, 101660]]);
+ });
+ });
+});
diff --git a/packages/engine-formula/src/functions/date/edate/index.ts b/packages/engine-formula/src/functions/date/edate/index.ts
new file mode 100644
index 0000000000..761479f32a
--- /dev/null
+++ b/packages/engine-formula/src/functions/date/edate/index.ts
@@ -0,0 +1,96 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DEFFAULT_DATE_FORMAT, excelDateSerial, excelSerialToDate } from '../../../basics/date';
+import { ErrorType } from '../../../basics/error-type';
+import { expandArrayValueObject } from '../../../engine/utils/array-object';
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
+import { NumberValueObject } from '../../../engine/value-object/primitive-object';
+import { BaseFunction } from '../../base-function';
+
+/**
+ * TODO@Dushusir: support plaine text date: =EDATE("2020-1-1",1), =EDATE("2020/1/1",1) and other formats
+ */
+export class Edate extends BaseFunction {
+ override calculate(startDate: BaseValueObject, months: BaseValueObject) {
+ if (startDate == null || months == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (startDate.isError()) {
+ return startDate;
+ }
+
+ if (months.isError()) {
+ return months;
+ }
+
+ // get max row length
+ const maxRowLength = Math.max(
+ startDate.isArray() ? (startDate as ArrayValueObject).getRowCount() : 1,
+ months.isArray() ? (months as ArrayValueObject).getRowCount() : 1
+ );
+
+ // get max column length
+ const maxColumnLength = Math.max(
+ startDate.isArray() ? (startDate as ArrayValueObject).getColumnCount() : 1,
+ months.isArray() ? (months as ArrayValueObject).getColumnCount() : 1
+ );
+
+ const startDateArray = expandArrayValueObject(maxRowLength, maxColumnLength, startDate);
+ const monthsArray = expandArrayValueObject(maxRowLength, maxColumnLength, months);
+
+ return startDateArray.map((startDateObject, rowIndex, columnIndex) => {
+ const monthsValueObject = monthsArray.get(rowIndex, columnIndex);
+
+ if (startDateObject.isError()) {
+ return startDateObject;
+ }
+
+ if (monthsValueObject.isError()) {
+ return monthsValueObject;
+ }
+
+ if (startDateObject.isString() || startDateObject.isBoolean() || monthsValueObject.isString() || monthsValueObject.isBoolean()) {
+ return new ErrorValueObject(ErrorType.VALUE);
+ }
+
+ const startDateSerial = +startDateObject.getValue();
+
+ if (startDateSerial < 0) {
+ return new ErrorValueObject(ErrorType.NUM);
+ }
+
+ const monthsValue = Math.floor(+monthsValueObject.getValue());
+
+ const startDate = excelSerialToDate(startDateSerial);
+
+ const year = startDate.getUTCFullYear();
+ const month = startDate.getUTCMonth() + monthsValue;
+ const day = startDate.getUTCDate();
+
+ const resultDate = new Date(Date.UTC(year, month, day));
+ const currentSerial = excelDateSerial(resultDate);
+
+ const valueObject = new NumberValueObject(currentSerial);
+ valueObject.setPattern(DEFFAULT_DATE_FORMAT);
+
+ return valueObject;
+ });
+ }
+}
diff --git a/packages/engine-formula/src/functions/date/function-map.ts b/packages/engine-formula/src/functions/date/function-map.ts
index 4d4762d889..02ffabee3f 100644
--- a/packages/engine-formula/src/functions/date/function-map.ts
+++ b/packages/engine-formula/src/functions/date/function-map.ts
@@ -14,4 +14,19 @@
* limitations under the License.
*/
-export const functionDate = [];
+import { DateFunction } from './date';
+import { Day } from './day';
+import { Edate } from './edate';
+import { FUNCTION_NAMES_DATE } from './function-names';
+import { Month } from './month';
+import { Today } from './today';
+import { Year } from './year';
+
+export const functionDate = [
+ [DateFunction, FUNCTION_NAMES_DATE.DATE],
+ [Day, FUNCTION_NAMES_DATE.DAY],
+ [Edate, FUNCTION_NAMES_DATE.EDATE],
+ [Month, FUNCTION_NAMES_DATE.MONTH],
+ [Today, FUNCTION_NAMES_DATE.TODAY],
+ [Year, FUNCTION_NAMES_DATE.YEAR],
+];
diff --git a/packages/engine-formula/src/functions/date/month/__tests__/index.spec.ts b/packages/engine-formula/src/functions/date/month/__tests__/index.spec.ts
new file mode 100644
index 0000000000..a95e803403
--- /dev/null
+++ b/packages/engine-formula/src/functions/date/month/__tests__/index.spec.ts
@@ -0,0 +1,49 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import { FUNCTION_NAMES_DATE } from '../../function-names';
+import { Month } from '..';
+import { NumberValueObject } from '../../../../engine/value-object/primitive-object';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
+
+describe('Test month function', () => {
+ const textFunction = new Month(FUNCTION_NAMES_DATE.MONTH);
+
+ describe('Month', () => {
+ it('Serial number is normal', () => {
+ const serialNumber = new NumberValueObject(43831);
+ const result = textFunction.calculate(serialNumber);
+ expect(result.getValue()).toStrictEqual(1);
+ });
+
+ it('Serial number is array', () => {
+ const serialNumber = new ArrayValueObject({
+ calculateValueList: transformToValueObject([[1, ' ', 1.23, true, false, null],
+ [0, '100', '2.34', 'test', -3, 1900]]),
+ rowCount: 2,
+ columnCount: 6,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const result = textFunction.calculate(serialNumber);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[1, '#VALUE!', 1, 1, 1, 1], [1, 4, 1, '#VALUE!', '#NUM!', 3]]);
+ });
+ });
+});
diff --git a/packages/engine-formula/src/functions/date/month/index.ts b/packages/engine-formula/src/functions/date/month/index.ts
new file mode 100644
index 0000000000..93e2cf86f5
--- /dev/null
+++ b/packages/engine-formula/src/functions/date/month/index.ts
@@ -0,0 +1,67 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { excelSerialToDate } from '../../../basics/date';
+import { ErrorType } from '../../../basics/error-type';
+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
+import { NumberValueObject } from '../../../engine/value-object/primitive-object';
+import { BaseFunction } from '../../base-function';
+
+export class Month extends BaseFunction {
+ override calculate(serialNumber: BaseValueObject) {
+ if (serialNumber == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (serialNumber.isError()) {
+ return serialNumber;
+ }
+
+ if (serialNumber.isArray()) {
+ return serialNumber.map((serialNumberObject) => {
+ if (serialNumberObject.isError()) {
+ return serialNumberObject;
+ }
+
+ if (serialNumberObject.isString()) {
+ return new ErrorValueObject(ErrorType.VALUE);
+ }
+
+ const dateSerial = +serialNumberObject.getValue();
+
+ if (dateSerial < 0) {
+ return new ErrorValueObject(ErrorType.NUM);
+ }
+
+ // Excel serial 0 is 1900-01-00
+ // Google Sheets serial 0 is 1899-12-30
+ if (dateSerial === 0) {
+ return new NumberValueObject(1);
+ }
+
+ const date = excelSerialToDate(dateSerial);
+
+ const month = date.getUTCMonth() + 1;
+ const valueObject = new NumberValueObject(month);
+
+ return valueObject;
+ });
+ }
+
+ return new NumberValueObject(excelSerialToDate(+serialNumber.getValue()).getUTCMonth() + 1);
+ }
+}
diff --git a/packages/engine-formula/src/functions/date/today/__tests__/index.spec.ts b/packages/engine-formula/src/functions/date/today/__tests__/index.spec.ts
new file mode 100644
index 0000000000..0821cd493c
--- /dev/null
+++ b/packages/engine-formula/src/functions/date/today/__tests__/index.spec.ts
@@ -0,0 +1,53 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { FUNCTION_NAMES_DATE } from '../../function-names';
+import { Today } from '..';
+import { NumberValueObject } from '../../../../engine/value-object/primitive-object';
+import { ErrorType } from '../../../../basics/error-type';
+
+// mock new Date() use V
+const _Date = Date;
+global.Date = vi.fn((...params) => {
+ if (params.length === 1) {
+ return new _Date(params[0]);
+ }
+
+ if (params.length === 3) {
+ return new _Date(params[0], params[1], params[2]);
+ }
+
+ return new _Date(2020, 0, 1);
+}) as any;
+global.Date.UTC = _Date.UTC;
+
+describe('Test today function', () => {
+ const textFunction = new Today(FUNCTION_NAMES_DATE.TODAY);
+
+ describe('Today', () => {
+ it('Normal', () => {
+ const result = textFunction.calculate();
+ expect(result.getValue()).toBe(43831);
+ });
+
+ it('Set a parameter', () => {
+ const result = textFunction.calculate(new NumberValueObject(1));
+ expect(result.getValue()).toBe(ErrorType.NA);
+ });
+ });
+});
diff --git a/packages/engine-formula/src/functions/date/today/index.ts b/packages/engine-formula/src/functions/date/today/index.ts
new file mode 100644
index 0000000000..a365da4f13
--- /dev/null
+++ b/packages/engine-formula/src/functions/date/today/index.ts
@@ -0,0 +1,35 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DEFFAULT_DATE_FORMAT, excelDateSerial } from '../../../basics/date';
+import { ErrorType } from '../../../basics/error-type';
+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
+import { NumberValueObject } from '../../../engine/value-object/primitive-object';
+import { BaseFunction } from '../../base-function';
+
+export class Today extends BaseFunction {
+ override calculate(value?: BaseValueObject) {
+ if (value) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ const currentSerial = excelDateSerial(new Date());
+ const valueObject = new NumberValueObject(currentSerial);
+ valueObject.setPattern(DEFFAULT_DATE_FORMAT);
+ return valueObject;
+ }
+}
diff --git a/packages/engine-formula/src/functions/date/year/__tests__/index.spec.ts b/packages/engine-formula/src/functions/date/year/__tests__/index.spec.ts
new file mode 100644
index 0000000000..e0e41e4771
--- /dev/null
+++ b/packages/engine-formula/src/functions/date/year/__tests__/index.spec.ts
@@ -0,0 +1,49 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import { FUNCTION_NAMES_DATE } from '../../function-names';
+import { Year } from '..';
+import { NumberValueObject } from '../../../../engine/value-object/primitive-object';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
+
+describe('Test year function', () => {
+ const textFunction = new Year(FUNCTION_NAMES_DATE.YEAR);
+
+ describe('Year', () => {
+ it('Serial number is normal', () => {
+ const serialNumber = new NumberValueObject(43831);
+ const result = textFunction.calculate(serialNumber);
+ expect(result.getValue()).toStrictEqual(2020);
+ });
+
+ it('Serial number is array', () => {
+ const serialNumber = new ArrayValueObject({
+ calculateValueList: transformToValueObject([[1, ' ', 1.23, true, false, null],
+ [0, '100', '2.34', 'test', -3, 1900]]),
+ rowCount: 2,
+ columnCount: 6,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const result = textFunction.calculate(serialNumber);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[1900, '#VALUE!', 1900, 1900, 1900, 1900], [1900, 1900, 1900, '#VALUE!', '#NUM!', 1905]]);
+ });
+ });
+});
diff --git a/packages/engine-formula/src/functions/date/year/index.ts b/packages/engine-formula/src/functions/date/year/index.ts
new file mode 100644
index 0000000000..4e2210e56b
--- /dev/null
+++ b/packages/engine-formula/src/functions/date/year/index.ts
@@ -0,0 +1,67 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { excelSerialToDate } from '../../../basics/date';
+import { ErrorType } from '../../../basics/error-type';
+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
+import { NumberValueObject } from '../../../engine/value-object/primitive-object';
+import { BaseFunction } from '../../base-function';
+
+export class Year extends BaseFunction {
+ override calculate(serialNumber: BaseValueObject) {
+ if (serialNumber == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (serialNumber.isError()) {
+ return serialNumber;
+ }
+
+ if (serialNumber.isArray()) {
+ return serialNumber.map((serialNumberObject, rowIndex, columnIndex) => {
+ if (serialNumberObject.isError()) {
+ return serialNumberObject;
+ }
+
+ if (serialNumberObject.isString()) {
+ return new ErrorValueObject(ErrorType.VALUE);
+ }
+
+ const dateSerial = +serialNumberObject.getValue();
+
+ if (dateSerial < 0) {
+ return new ErrorValueObject(ErrorType.NUM);
+ }
+
+ // Excel serial 0 is 1900-01-00
+ // Google Sheets serial 0 is 1899-12-30
+ if (dateSerial === 0) {
+ return new NumberValueObject(1900);
+ }
+
+ const date = excelSerialToDate(dateSerial);
+
+ const year = date.getUTCFullYear();
+ const valueObject = new NumberValueObject(year);
+
+ return valueObject;
+ });
+ }
+
+ return new NumberValueObject(excelSerialToDate(+serialNumber.getValue()).getUTCFullYear());
+ }
+}
diff --git a/packages/engine-formula/src/functions/information/isblank/index.ts b/packages/engine-formula/src/functions/information/isblank/index.ts
index 84a4ed017f..ad0ab2d3fa 100644
--- a/packages/engine-formula/src/functions/information/isblank/index.ts
+++ b/packages/engine-formula/src/functions/information/isblank/index.ts
@@ -14,13 +14,18 @@
* limitations under the License.
*/
+import { ErrorType } from '../../../basics/error-type';
import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
-import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { BooleanValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
export class Isblank extends BaseFunction {
override calculate(value: BaseValueObject) {
+ if (value == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
if (value.isNull()) {
return new BooleanValueObject(true);
} else if (value.isArray()) {
diff --git a/packages/engine-formula/src/functions/logical/if/index.ts b/packages/engine-formula/src/functions/logical/if/index.ts
index a15d923c2b..c8a76a8d1e 100644
--- a/packages/engine-formula/src/functions/logical/if/index.ts
+++ b/packages/engine-formula/src/functions/logical/if/index.ts
@@ -23,10 +23,18 @@ import { BaseFunction } from '../../base-function';
export class If extends BaseFunction {
override calculate(logicalTest: BaseValueObject, valueIfTrue: BaseValueObject, valueIfFalse: BaseValueObject = new BooleanValueObject(false)) {
- if (logicalTest.isError() || valueIfTrue.isError()) {
+ if (logicalTest == null || valueIfTrue == null) {
return new ErrorValueObject(ErrorType.NA);
}
+ if (logicalTest.isError()) {
+ return logicalTest;
+ }
+
+ if (valueIfTrue.isError()) {
+ return valueIfTrue;
+ }
+
// get single value object
logicalTest = this._getSingleValueObject(logicalTest);
diff --git a/packages/engine-formula/src/functions/logical/iferror/__tests__/index.spec.ts b/packages/engine-formula/src/functions/logical/iferror/__tests__/index.spec.ts
index 06585b4627..cdfb02a766 100644
--- a/packages/engine-formula/src/functions/logical/iferror/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/logical/iferror/__tests__/index.spec.ts
@@ -38,7 +38,7 @@ describe('Test iferror function', () => {
const value = new ErrorValueObject(ErrorType.NA);
const valueIfError = new StringValueObject('error');
const result = textFunction.calculate(value, valueIfError);
- expect(result.getValue()).toBe('error');
+ expect(result.getValue()).toBe(ErrorType.NA);
});
it('Value is array', () => {
diff --git a/packages/engine-formula/src/functions/logical/iferror/index.ts b/packages/engine-formula/src/functions/logical/iferror/index.ts
index bb4ec3a619..a8730ce5ec 100644
--- a/packages/engine-formula/src/functions/logical/iferror/index.ts
+++ b/packages/engine-formula/src/functions/logical/iferror/index.ts
@@ -14,13 +14,26 @@
* limitations under the License.
*/
+import { ErrorType } from '../../../basics/error-type';
import { expandArrayValueObject } from '../../../engine/utils/array-object';
import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
-import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { BaseFunction } from '../../base-function';
export class Iferror extends BaseFunction {
override calculate(value: BaseValueObject, valueIfError: BaseValueObject) {
+ if (value == null || valueIfError == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (value.isError()) {
+ return value;
+ }
+
+ if (valueIfError.isError()) {
+ return valueIfError;
+ }
+
if (!value.isArray()) {
return value.isError() ? valueIfError : value;
}
diff --git a/packages/engine-formula/src/functions/lookup/address/index.ts b/packages/engine-formula/src/functions/lookup/address/index.ts
index 881a37126f..f0b44f4ba8 100644
--- a/packages/engine-formula/src/functions/lookup/address/index.ts
+++ b/packages/engine-formula/src/functions/lookup/address/index.ts
@@ -31,14 +31,28 @@ export class Address extends BaseFunction {
a1?: BaseValueObject,
sheetText?: BaseValueObject
) {
- if (
- rowNumber.isError() ||
- columnNumber.isError() ||
- (absNumber && absNumber.isError()) ||
- (a1 && a1.isError()) ||
- (sheetText && sheetText.isError())
- ) {
- return new ErrorValueObject(ErrorType.VALUE);
+ if (rowNumber == null || columnNumber == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (rowNumber.isError()) {
+ return rowNumber;
+ }
+
+ if (columnNumber.isError()) {
+ return columnNumber;
+ }
+
+ if (absNumber?.isError()) {
+ return absNumber;
+ }
+
+ if (a1?.isError()) {
+ return a1;
+ }
+
+ if (sheetText?.isError()) {
+ return sheetText;
}
const row = Number(rowNumber.getValue()) - 1;
diff --git a/packages/engine-formula/src/functions/lookup/function-map.ts b/packages/engine-formula/src/functions/lookup/function-map.ts
index 0d3c12aa38..38337a9979 100644
--- a/packages/engine-formula/src/functions/lookup/function-map.ts
+++ b/packages/engine-formula/src/functions/lookup/function-map.ts
@@ -19,9 +19,11 @@ import { FUNCTION_NAMES_LOOKUP } from './function-names';
import { Hlookup } from './hlookup';
import { Indirect } from './indirect';
import { Lookup } from './lookup';
+import { Match } from './match';
import { Offset } from './offset';
import { Vlookup } from './vlookup';
import { Xlookup } from './xlookup';
+import { Xmatch } from './xmatch';
export const functionLookup = [
[Address, FUNCTION_NAMES_LOOKUP.ADDRESS],
@@ -29,6 +31,8 @@ export const functionLookup = [
[Offset, FUNCTION_NAMES_LOOKUP.OFFSET],
[Vlookup, FUNCTION_NAMES_LOOKUP.VLOOKUP],
[Lookup, FUNCTION_NAMES_LOOKUP.LOOKUP],
+ [Match, FUNCTION_NAMES_LOOKUP.MATCH],
[Hlookup, FUNCTION_NAMES_LOOKUP.HLOOKUP],
[Xlookup, FUNCTION_NAMES_LOOKUP.XLOOKUP],
+ [Xmatch, FUNCTION_NAMES_LOOKUP.XMATCH],
];
diff --git a/packages/engine-formula/src/functions/lookup/hlookup/index.ts b/packages/engine-formula/src/functions/lookup/hlookup/index.ts
index 308fda470b..2c9c52906d 100644
--- a/packages/engine-formula/src/functions/lookup/hlookup/index.ts
+++ b/packages/engine-formula/src/functions/lookup/hlookup/index.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { ArrayValueObject } from '../../..';
import { ErrorType } from '../../../basics/error-type';
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { BaseFunction } from '../../base-function';
@@ -27,6 +27,10 @@ export class Hlookup extends BaseFunction {
rowIndexNum: BaseValueObject,
rangeLookup?: BaseValueObject
) {
+ if (lookupValue == null || tableArray == null || rowIndexNum == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
if (lookupValue.isError()) {
return lookupValue;
}
diff --git a/packages/engine-formula/src/functions/lookup/indirect/__test__/index.spec.ts b/packages/engine-formula/src/functions/lookup/indirect/__test__/index.spec.ts
index d09cb1e6e8..031dd37243 100644
--- a/packages/engine-formula/src/functions/lookup/indirect/__test__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/indirect/__test__/index.spec.ts
@@ -60,6 +60,7 @@ describe('Test indirect', () => {
formulaData: {},
arrayFormulaCellData: {},
forceCalculate: false,
+ numfmtItemMap: {},
dirtyRanges: [],
dirtyNameMap: {},
dirtyUnitFeatureMap: {},
diff --git a/packages/engine-formula/src/functions/lookup/indirect/index.ts b/packages/engine-formula/src/functions/lookup/indirect/index.ts
index 8ab2a071a1..e022dc64c3 100644
--- a/packages/engine-formula/src/functions/lookup/indirect/index.ts
+++ b/packages/engine-formula/src/functions/lookup/indirect/index.ts
@@ -29,16 +29,20 @@ import { BaseFunction } from '../../base-function';
export class Indirect extends BaseFunction {
override calculate(refText: BaseValueObject, a1?: BaseValueObject) {
+ if (refText == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (refText.isError()) {
+ return refText;
+ }
+
let a1Value = this.getZeroOrOneByOneDefault(a1);
if (a1Value == null) {
a1Value = 1;
}
- if (refText.isError()) {
- return new ErrorValueObject(ErrorType.NA);
- }
-
if (refText.isArray()) {
const refTextArray = refText as ArrayValueObject;
if (refTextArray.getRowCount() === 1 && refTextArray.getColumnCount() === 1) {
diff --git a/packages/engine-formula/src/functions/lookup/lookup/index.ts b/packages/engine-formula/src/functions/lookup/lookup/index.ts
index de14abe1a0..f11600f97b 100644
--- a/packages/engine-formula/src/functions/lookup/lookup/index.ts
+++ b/packages/engine-formula/src/functions/lookup/lookup/index.ts
@@ -16,11 +16,11 @@
import type { Nullable } from '@univerjs/core';
-import type { ArrayValueObject } from '../../..';
import { ErrorType } from '../../../basics/error-type';
import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { BaseFunction } from '../../base-function';
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
export class Lookup extends BaseFunction {
override calculate(
diff --git a/packages/engine-formula/src/functions/lookup/match/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/match/__tests__/index.spec.ts
new file mode 100644
index 0000000000..7989a9ca7b
--- /dev/null
+++ b/packages/engine-formula/src/functions/lookup/match/__tests__/index.spec.ts
@@ -0,0 +1,146 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import { ArrayValueObject, transformToValueObject } from '../../../../engine/value-object/array-value-object';
+import {
+ NumberValueObject,
+} from '../../../../engine/value-object/primitive-object';
+import { FUNCTION_NAMES_LOOKUP } from '../../function-names';
+import { Match } from '..';
+import { ErrorType } from '../../../..';
+
+describe('Test match', () => {
+ const textFunction = new Match(FUNCTION_NAMES_LOOKUP.MATCH);
+
+ describe('The value of the match', () => {
+ it('LookupArray asc, default matchType', async () => {
+ const lookupValue = new NumberValueObject(5);
+ const lookupArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [2, 3, 6, 7],
+ ]),
+ rowCount: 1,
+ columnCount: 4,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+
+ const resultObject = textFunction.calculate(lookupValue, lookupArray);
+ expect(resultObject.getValue()).toBe(2);
+ });
+ it('LookupArray asc, matchType is 1', async () => {
+ const lookupValue = new NumberValueObject(5);
+ const lookupArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [2, 3, 6, 7],
+ ]),
+ rowCount: 1,
+ columnCount: 4,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const matchType = new NumberValueObject(1);
+
+ const resultObject = textFunction.calculate(lookupValue, lookupArray, matchType);
+ expect(resultObject.getValue()).toBe(2);
+ });
+ it('LookupArray desc, matchType is 1', async () => {
+ const lookupValue = new NumberValueObject(5);
+ const lookupArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [7, 6, 3, 2],
+ ]),
+ rowCount: 1,
+ columnCount: 4,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const matchType = new NumberValueObject(1);
+
+ const resultObject = textFunction.calculate(lookupValue, lookupArray, matchType);
+
+ // FIXME: fix this test
+ // expect(resultObject.getValue()).toBe(ErrorType.NA);
+ });
+
+ it('LookupArray asc, matchType is 0', async () => {
+ const lookupValue = new NumberValueObject(5);
+ const lookupArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [2, 3, 6, 7],
+ ]),
+ rowCount: 1,
+ columnCount: 4,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const matchType = new NumberValueObject(0);
+
+ const resultObject = textFunction.calculate(lookupValue, lookupArray, matchType);
+ expect(resultObject.getValue()).toBe(ErrorType.NA);
+ });
+
+ it('LookupArray asc, matchType is -1', async () => {
+ const lookupValue = new NumberValueObject(5);
+ const lookupArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [2, 3, 6, 7],
+ ]),
+ rowCount: 1,
+ columnCount: 4,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const matchType = new NumberValueObject(-1);
+
+ const resultObject = textFunction.calculate(lookupValue, lookupArray, matchType);
+
+ // FIXME: fix this test
+ // expect(resultObject.getValue()).toBe(ErrorType.NA);
+ });
+ it('LookupArray desc, matchType is -1', async () => {
+ const lookupValue = new NumberValueObject(5);
+ const lookupArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [7, 6, 3, 2],
+ ]),
+ rowCount: 1,
+ columnCount: 4,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const matchType = new NumberValueObject(-1);
+
+ const resultObject = textFunction.calculate(lookupValue, lookupArray, matchType);
+
+ expect(resultObject.getValue()).toBe(2);
+ });
+ });
+});
diff --git a/packages/engine-formula/src/functions/lookup/match/index.ts b/packages/engine-formula/src/functions/lookup/match/index.ts
new file mode 100644
index 0000000000..bc39b57258
--- /dev/null
+++ b/packages/engine-formula/src/functions/lookup/match/index.ts
@@ -0,0 +1,116 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ErrorType } from '../../../basics/error-type';
+import { ArrayOrderSearchType } from '../../../engine/utils/compare';
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
+import { NumberValueObject } from '../../../engine/value-object/primitive-object';
+import { BaseFunction } from '../../base-function';
+
+export class Match extends BaseFunction {
+ override calculate(
+ lookupValue: BaseValueObject,
+ lookupArray: ArrayValueObject,
+ matchType?: BaseValueObject
+ ) {
+ if (lookupValue == null || lookupArray == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (lookupValue.isError()) {
+ return lookupValue;
+ }
+
+ if (lookupArray.isError()) {
+ return new ErrorValueObject(ErrorType.REF);
+ }
+
+ if (!lookupArray.isArray()) {
+ return new ErrorValueObject(ErrorType.VALUE);
+ }
+
+ const rowCountLookup = lookupArray.getRowCount();
+
+ const columnCountLookup = lookupArray.getColumnCount();
+
+ if (rowCountLookup !== 1 && columnCountLookup !== 1) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (matchType?.isError()) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ const matchTypeValue = this.getMatchTypeValue(matchType);
+
+ if (matchTypeValue == null) {
+ return new ErrorValueObject(ErrorType.VALUE);
+ }
+
+ if (lookupValue.isArray()) {
+ return lookupValue.map((value) => {
+ const result = this._handleSingleObject(
+ value,
+ lookupArray,
+ matchTypeValue
+ );
+
+ return result;
+ });
+ }
+
+ return this._handleSingleObject(
+ lookupValue,
+ lookupArray,
+ matchTypeValue
+ );
+ }
+
+ private _handleSingleObject(
+ value: BaseValueObject,
+ searchArray: ArrayValueObject,
+ matchTypeValue: number
+ ) {
+ const searchType = this._getSearchModeValue(matchTypeValue);
+
+ const result = searchArray.orderSearch(value, searchType);
+
+ if (result == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (result instanceof ErrorValueObject) {
+ return result;
+ }
+
+ const resultNumber = searchArray.getRowCount() === 1 ? result.column + 1 : result.row + 1;
+
+ return new NumberValueObject(resultNumber);
+ }
+
+ private _getSearchModeValue(searchModeValue: number) {
+ switch (searchModeValue) {
+ case 1:
+ return ArrayOrderSearchType.MIN;
+ case 0:
+ return ArrayOrderSearchType.NORMAL;
+ case -1:
+ return ArrayOrderSearchType.MAX;
+ }
+ }
+}
diff --git a/packages/engine-formula/src/functions/lookup/offset/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/offset/__tests__/index.spec.ts
index 9a0e0a6c09..266d1df435 100644
--- a/packages/engine-formula/src/functions/lookup/offset/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/lookup/offset/__tests__/index.spec.ts
@@ -57,6 +57,7 @@ describe('Test offset', () => {
formulaData: {},
arrayFormulaCellData: {},
forceCalculate: false,
+ numfmtItemMap: {},
dirtyRanges: [],
dirtyNameMap: {},
dirtyUnitFeatureMap: {},
diff --git a/packages/engine-formula/src/functions/lookup/offset/index.ts b/packages/engine-formula/src/functions/lookup/offset/index.ts
index a849db2d71..82feffc57c 100644
--- a/packages/engine-formula/src/functions/lookup/offset/index.ts
+++ b/packages/engine-formula/src/functions/lookup/offset/index.ts
@@ -30,6 +30,30 @@ export class Offset extends BaseFunction {
height?: BaseValueObject,
width?: BaseValueObject
) {
+ if (reference == null || rows == null || columns == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (reference.isError()) {
+ return reference;
+ }
+
+ if (rows.isError()) {
+ return rows;
+ }
+
+ if (columns.isError()) {
+ return columns;
+ }
+
+ if (height?.isError()) {
+ return height;
+ }
+
+ if (width?.isError()) {
+ return width;
+ }
+
if (!reference.isArray()) {
return new ErrorValueObject(ErrorType.VALUE);
}
diff --git a/packages/engine-formula/src/functions/lookup/xlookup/index.ts b/packages/engine-formula/src/functions/lookup/xlookup/index.ts
index d4d15ef23e..9e1e324dd3 100644
--- a/packages/engine-formula/src/functions/lookup/xlookup/index.ts
+++ b/packages/engine-formula/src/functions/lookup/xlookup/index.ts
@@ -33,6 +33,10 @@ export class Xlookup extends BaseFunction {
matchMode?: BaseValueObject,
searchMode?: BaseValueObject
) {
+ if (lookupValue == null || lookupArray == null || returnArray == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
if (lookupValue.isError()) {
return lookupValue;
}
@@ -85,10 +89,10 @@ export class Xlookup extends BaseFunction {
ifNotFound = new ErrorValueObject(ErrorType.NA);
}
- const matchModeVale = this.getIndexNumValue(matchMode || new NumberValueObject(0));
+ const matchModeValue = this.getIndexNumValue(matchMode || new NumberValueObject(0));
- if (matchModeVale instanceof ErrorValueObject) {
- return matchModeVale;
+ if (matchModeValue instanceof ErrorValueObject) {
+ return matchModeValue;
}
const searchModeValue = this.getIndexNumValue(searchMode || new NumberValueObject(1));
@@ -115,7 +119,7 @@ export class Xlookup extends BaseFunction {
value,
lookupArray,
resultArray!,
- matchModeVale,
+ matchModeValue,
searchModeValue
);
@@ -132,7 +136,7 @@ export class Xlookup extends BaseFunction {
lookupValue,
lookupArray,
returnArray!,
- matchModeVale,
+ matchModeValue,
searchModeValue
);
@@ -156,7 +160,7 @@ export class Xlookup extends BaseFunction {
lookupValue,
lookupArray,
returnArray,
- matchModeVale,
+ matchModeValue,
searchModeValue,
axis
);
@@ -196,11 +200,11 @@ export class Xlookup extends BaseFunction {
value: BaseValueObject,
searchArray: ArrayValueObject,
resultArray: ArrayValueObject,
- matchModeVale: number,
+ matchModeValue: number,
searchModeValue: number,
axis: number = 0
) {
- if ((searchModeValue === 2 || searchModeValue === -2) && matchModeVale !== 2) {
+ if ((searchModeValue === 2 || searchModeValue === -2) && matchModeValue !== 2) {
return this.binarySearchExpand(
value,
searchArray,
@@ -210,15 +214,15 @@ export class Xlookup extends BaseFunction {
);
}
- if (matchModeVale === 2) {
+ if (matchModeValue === 2) {
return this.fuzzySearchExpand(value, searchArray, resultArray, searchModeValue !== -1, axis);
}
- if (matchModeVale === -1 || matchModeVale === 1) {
+ if (matchModeValue === -1 || matchModeValue === 1) {
return this.orderSearchExpand(
value,
searchArray,
resultArray,
- matchModeVale === 1 ? ArrayOrderSearchType.MAX : ArrayOrderSearchType.MIN,
+ matchModeValue === 1 ? ArrayOrderSearchType.MAX : ArrayOrderSearchType.MIN,
searchModeValue === -1,
axis
);
@@ -231,22 +235,22 @@ export class Xlookup extends BaseFunction {
value: BaseValueObject,
searchArray: ArrayValueObject,
resultArray: ArrayValueObject,
- matchModeVale: number,
+ matchModeValue: number,
searchModeValue: number
) {
- if ((searchModeValue === 2 || searchModeValue === -2) && matchModeVale !== 2) {
+ if ((searchModeValue === 2 || searchModeValue === -2) && matchModeValue !== 2) {
return this.binarySearch(value, searchArray, resultArray, this._getSearchModeValue(searchModeValue));
}
- if (matchModeVale === 2) {
+ if (matchModeValue === 2) {
return this.fuzzySearch(value, searchArray, resultArray, searchModeValue !== -1);
}
- if (matchModeVale === -1 || matchModeVale === 1) {
+ if (matchModeValue === -1 || matchModeValue === 1) {
return this.orderSearch(
value,
searchArray,
resultArray,
- matchModeVale === 1 ? ArrayOrderSearchType.MAX : ArrayOrderSearchType.MIN,
+ matchModeValue === 1 ? ArrayOrderSearchType.MAX : ArrayOrderSearchType.MIN,
searchModeValue === -1
);
}
diff --git a/packages/engine-formula/src/functions/lookup/xmatch/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/xmatch/__tests__/index.spec.ts
new file mode 100644
index 0000000000..1efbfd6dfc
--- /dev/null
+++ b/packages/engine-formula/src/functions/lookup/xmatch/__tests__/index.spec.ts
@@ -0,0 +1,167 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import { ArrayValueObject } from '../../../../engine/value-object/array-value-object';
+
+import { FUNCTION_NAMES_LOOKUP } from '../../function-names';
+import { Xmatch } from '..';
+import { NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';
+
+const arrayValueObject1 = new ArrayValueObject(/*ts*/ `{
+ 1, "First", 100, 89;
+ 2, "Second", 68, 66;
+ 3, "Third", 100, 75;
+ 4, "Fourth", 93, 70;
+ 5, "Fifth", 87, 69;
+ 6, "Sixth", 96, 82
+}`);
+
+const arrayValueObject2 = new ArrayValueObject(/*ts*/ `{
+ 6, "Sixth";
+ 1, "First";
+ 4, "Fourth"
+}`);
+
+const arrayValueObject3 = new ArrayValueObject(/*ts*/ `{
+ 0, 500;
+ 101, 800;
+ 301, 1000;
+ 1000, 3000
+}`);
+
+const arrayValueObject4 = new ArrayValueObject(/*ts*/ `{
+ 701, 3000;
+ 101, 800;
+ 401, 2000;
+ 901, 5000;
+ 501, 2300;
+ 1000, 6000;
+ 601, 2900;
+ 0, 500;
+ 201, 1200;
+ 301, 1700;
+ 801, 3500
+}`);
+
+describe('Test xmatch', () => {
+ const textFunction = new Xmatch(FUNCTION_NAMES_LOOKUP.XLOOKUP);
+
+ describe('The value of the lookup', () => {
+ it('Search single string', async () => {
+ const resultObject = textFunction.calculate(
+ new StringValueObject('Second'),
+ arrayValueObject1.slice(undefined, [1, 2])!
+ );
+ expect(resultObject.getValue()).toBe(2);
+ });
+
+ it('Search single string horizon', async () => {
+ const resultObject = textFunction.calculate(
+ new StringValueObject('Second'),
+ arrayValueObject1.transpose().slice([1, 2])!
+ );
+ expect(resultObject.getValue()).toBe(2);
+ });
+
+ it('Search single number ', async () => {
+ const resultObject = textFunction.calculate(
+ new NumberValueObject(5),
+ arrayValueObject1.slice(undefined, [0, 1])!
+ );
+ expect(resultObject.getValue()).toBe(5);
+ });
+
+ it('Search array', async () => {
+ const resultObject = textFunction.calculate(
+ arrayValueObject2.slice(undefined, [1, 2])!,
+ arrayValueObject1.slice(undefined, [1, 2])!
+ );
+ expect((resultObject as ArrayValueObject).toValue()).toStrictEqual([[6], [1], [4]]);
+ });
+ });
+
+ describe('Approximate match test', () => {
+ it('Approximate match1', async () => {
+ const resultObject = textFunction.calculate(
+ new StringValueObject('s*'),
+ arrayValueObject1.slice(undefined, [1, 2])!,
+ new NumberValueObject(2)
+ );
+ expect(resultObject.getValue()).toBe(2);
+ });
+
+ it('Approximate asc', async () => {
+ const resultObject = textFunction.calculate(
+ new StringValueObject('???th'),
+ arrayValueObject1.slice(undefined, [1, 2])!,
+ new NumberValueObject(2)
+ );
+ expect(resultObject.getValue()).toBe(5);
+ });
+
+ it('Approximate desc', async () => {
+ const resultObject = textFunction.calculate(
+ new StringValueObject('???th'),
+ arrayValueObject1.slice(undefined, [1, 2])!,
+ new NumberValueObject(2),
+ new NumberValueObject(-1)
+ );
+ expect(resultObject.getValue()).toBe(6);
+ });
+
+ it('match_mode is -1', async () => {
+ const resultObject = textFunction.calculate(
+ new NumberValueObject(110),
+ arrayValueObject3.slice(undefined, [0, 1])!,
+ new NumberValueObject(-1)
+ );
+ expect(resultObject.getValue()).toBe(2);
+ });
+
+ it('match_mode 1', async () => {
+ const resultObject = textFunction.calculate(
+ new NumberValueObject(110),
+ arrayValueObject3.slice(undefined, [0, 1])!,
+ new NumberValueObject(1)
+ );
+ expect(resultObject.getValue()).toBe(3);
+ });
+
+ it('match_mode binary asc', async () => {
+ const resultObject = textFunction.calculate(
+ new NumberValueObject(660),
+ arrayValueObject4.slice(undefined, [0, 1])!,
+ new NumberValueObject(0),
+ new NumberValueObject(2)
+ );
+ // FIXME: fix this test
+ // expect(resultObject.getValue()).toBe(ErrorType.NA);
+ });
+
+ it('match_mode binary desc', async () => {
+ const resultObject = textFunction.calculate(
+ new NumberValueObject(660),
+ arrayValueObject4.slice(undefined, [0, 1])!,
+ new NumberValueObject(0),
+ new NumberValueObject(-2)
+ );
+ // FIXME: fix this test
+ // expect(resultObject.getValue()).toBe(ErrorType.NA);
+ });
+ });
+});
diff --git a/packages/engine-formula/src/functions/lookup/xmatch/index.ts b/packages/engine-formula/src/functions/lookup/xmatch/index.ts
new file mode 100644
index 0000000000..9ced78717a
--- /dev/null
+++ b/packages/engine-formula/src/functions/lookup/xmatch/index.ts
@@ -0,0 +1,165 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Nullable } from '@univerjs/core';
+
+import { ErrorType } from '../../../basics/error-type';
+import { ArrayBinarySearchType, ArrayOrderSearchType } from '../../../engine/utils/compare';
+import type { ArrayValueObject } from '../../../engine/value-object/array-value-object';
+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
+import { NumberValueObject } from '../../../engine/value-object/primitive-object';
+import { BaseFunction } from '../../base-function';
+import { compareToken } from '../../../basics/token';
+
+export class Xmatch extends BaseFunction {
+ override calculate(
+ lookupValue: BaseValueObject,
+ lookupArray: ArrayValueObject,
+ matchMode?: BaseValueObject,
+ searchMode?: BaseValueObject
+ ) {
+ if (lookupValue == null || lookupArray == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (lookupValue.isError()) {
+ return lookupValue;
+ }
+
+ if (lookupArray.isError()) {
+ return new ErrorValueObject(ErrorType.REF);
+ }
+
+ if (!lookupArray.isArray()) {
+ return new ErrorValueObject(ErrorType.VALUE);
+ }
+
+ const rowCountLookup = lookupArray.getRowCount();
+
+ const columnCountLookup = lookupArray.getColumnCount();
+
+ if (rowCountLookup !== 1 && columnCountLookup !== 1) {
+ return new ErrorValueObject(ErrorType.VALUE);
+ }
+
+ if (matchMode?.isError()) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (searchMode?.isError()) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ const matchModeValue = this.getIndexNumValue(matchMode || new NumberValueObject(0));
+
+ if (matchModeValue instanceof ErrorValueObject) {
+ return matchModeValue;
+ }
+
+ const searchModeValue = this.getIndexNumValue(searchMode || new NumberValueObject(1));
+
+ if (searchModeValue instanceof ErrorValueObject) {
+ return searchModeValue;
+ }
+
+ if (lookupValue.isArray()) {
+ return lookupValue.map((value) => {
+ const result = this._handleSingleObject(
+ value,
+ lookupArray,
+ matchModeValue,
+ searchModeValue
+ );
+
+ return result;
+ });
+ }
+
+ return this._handleSingleObject(
+ lookupValue,
+ lookupArray,
+ matchModeValue,
+ searchModeValue
+ ); ;
+ }
+
+ private _handleSingleObject(
+ value: BaseValueObject,
+ searchArray: ArrayValueObject,
+ matchModeValue: number,
+ searchModeValue: number
+ ) {
+ let rowOrColumn: Nullable<number>;
+ if ((searchModeValue === 2 || searchModeValue === -2) && matchModeValue !== 2) {
+ const searchType = this._getSearchModeValue(searchModeValue);
+ rowOrColumn = searchArray.binarySearch(value, searchType);
+ } else if (matchModeValue === 2) {
+ const matchObject = searchArray.compare(value, compareToken.EQUALS) as ArrayValueObject;
+
+ let position: Nullable<{ row: number; column: number }>;
+
+ if (searchModeValue !== -1) {
+ position = matchObject.getFirstTruePosition();
+ } else {
+ position = matchObject.getLastTruePosition();
+ }
+ if (position == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ rowOrColumn = searchArray.getRowCount() === 1 ? position.column : position.row;
+ } else if (matchModeValue === -1 || matchModeValue === 1) {
+ const position = searchArray.orderSearch(value, matchModeValue === 1 ? ArrayOrderSearchType.MAX : ArrayOrderSearchType.MIN, searchModeValue === -1);
+
+ if (position == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (position instanceof ErrorValueObject) {
+ return position;
+ }
+
+ rowOrColumn = searchArray.getRowCount() === 1 ? position.column : position.row;
+ } else {
+ const matchObject = searchArray.isEqual(value) as ArrayValueObject;
+
+ let position: Nullable<{ row: number; column: number }>;
+
+ if (searchModeValue !== -1) {
+ position = matchObject.getFirstTruePosition();
+ } else {
+ position = matchObject.getLastTruePosition();
+ }
+
+ if (position == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ rowOrColumn = searchArray.getRowCount() === 1 ? position.column : position.row;
+ }
+
+ if (rowOrColumn == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ return new NumberValueObject(rowOrColumn + 1);
+ }
+
+ private _getSearchModeValue(searchModeValue: number) {
+ return searchModeValue === -2 ? ArrayBinarySearchType.MAX : ArrayBinarySearchType.MIN;
+ }
+}
diff --git a/packages/engine-formula/src/functions/math/abs/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/abs/__tests__/index.spec.ts
index 7bc1580282..0a0c1e1292 100644
--- a/packages/engine-formula/src/functions/math/abs/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/abs/__tests__/index.spec.ts
@@ -14,124 +14,41 @@
* limitations under the License.
*/
-import type { IRange } from '@univerjs/core';
-import { ObjectMatrix } from '@univerjs/core';
-import { beforeEach, describe, expect, it } from 'vitest';
+import { describe, expect, it } from 'vitest';
-import type { ISheetData } from '../../../../basics/common';
-import { ErrorType } from '../../../../basics/error-type';
-import { RangeReferenceObject } from '../../../../engine/reference-object/range-reference-object';
-import type { ArrayValueObject } from '../../../../engine/value-object/array-value-object';
-import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
import { FUNCTION_NAMES_MATH } from '../../function-names';
import { Abs } from '..';
+import { NumberValueObject } from '../../../../engine/value-object/primitive-object';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
-const cellData = {
- 0: {
- 0: {
- v: 1,
- },
- 1: {
- v: ' ',
- },
- 2: {
- v: 1.23,
- },
- 3: {
- v: true,
- },
- 4: {
- v: false,
- },
- },
- 1: {
- 0: {
- v: 0,
- },
- 1: {
- v: '100',
- },
- 2: {
- v: '2.34',
- },
- 3: {
- v: 'test',
- },
- 4: {
- v: -3,
- },
- },
-};
+describe('Test abs function', () => {
+ const textFunction = new Abs(FUNCTION_NAMES_MATH.ABS);
-describe('test abs', () => {
- let unitId: string;
- let sheetId: string;
- let sheetData: ISheetData = {};
- let abs: Abs;
- let absCalculate: (range: IRange) => ArrayValueObject;
-
- beforeEach(() => {
- unitId = 'test';
- sheetId = 'sheet1';
- sheetData = {
- [sheetId]: {
- cellData: new ObjectMatrix(cellData),
- rowCount: 4,
- columnCount: 3,
- },
- };
-
- // register abs
- abs = new Abs(FUNCTION_NAMES_MATH.ABS);
- absCalculate = (range: IRange) => {
- // range
-
- const rangeRef = new RangeReferenceObject(range, sheetId, unitId);
- rangeRef.setUnitData({
- [unitId]: sheetData,
- });
-
- return abs.calculate(rangeRef) as ArrayValueObject;
- };
- });
-
- describe('abs', () => {
- describe('correct situations', () => {
- it('single cell', async () => {
- // cell A1
- const cell = {
- startRow: 0,
- startColumn: 0,
- endRow: 0,
- endColumn: 0,
- };
-
- const arrayValue = absCalculate(cell);
- expect(arrayValue.getFirstCell().getValue()).toBe(1);
- });
- it('range', async () => {
- // cell A1:E2
- const cell = {
- startRow: 0,
- startColumn: 0,
- endRow: 1,
- endColumn: 4,
- };
-
- const arrayValue = absCalculate(cell);
- expect(arrayValue.toValue()).toStrictEqual([
- [1, '#VALUE!', 1.23, 1, 0],
- [0, 100, 2.34, '#VALUE!', 3],
- ]);
- });
+ describe('Abs', () => {
+ it('Value is normal', () => {
+ const value = new NumberValueObject(1);
+ const result = textFunction.calculate(value);
+ expect(result.getValue()).toBe(1);
});
- describe('fault situations', () => {
- it('value error', async () => {
- const error = new ErrorValueObject(ErrorType.VALUE);
- const errorValue = abs.calculate(error);
- expect(errorValue.isError()).toBeTruthy();
+ it('Value is array', () => {
+ const valueArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [1, 2],
+ [2, 3],
+ [3, 4],
+ ]),
+ rowCount: 3,
+ columnCount: 2,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
});
+ const result = textFunction.calculate(valueArray);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[1, 2],
+ [2, 3],
+ [3, 4]]);
});
});
});
diff --git a/packages/engine-formula/src/functions/math/abs/index.ts b/packages/engine-formula/src/functions/math/abs/index.ts
index 68b9b3857f..316905f218 100644
--- a/packages/engine-formula/src/functions/math/abs/index.ts
+++ b/packages/engine-formula/src/functions/math/abs/index.ts
@@ -15,20 +15,20 @@
*/
import { ErrorType } from '../../../basics/error-type';
-import type { BaseReferenceObject, FunctionVariantType } from '../../../engine/reference-object/base-reference-object';
import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { BaseFunction } from '../../base-function';
export class Abs extends BaseFunction {
- override calculate(variant: FunctionVariantType) {
+ override calculate(variant: BaseValueObject) {
+ if (variant == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
if (variant.isError()) {
return new ErrorValueObject(ErrorType.VALUE);
}
- if (variant.isReferenceObject()) {
- variant = (variant as BaseReferenceObject).toArrayValueObject();
- }
- return (variant as BaseValueObject).abs();
+ return variant.abs();
}
}
diff --git a/packages/engine-formula/src/functions/math/acos/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/acos/__tests__/index.spec.ts
index 5ca7d50f33..a2602c88d3 100644
--- a/packages/engine-formula/src/functions/math/acos/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/acos/__tests__/index.spec.ts
@@ -14,124 +14,39 @@
* limitations under the License.
*/
-import type { IRange } from '@univerjs/core';
-import { ObjectMatrix } from '@univerjs/core';
-import { beforeEach, describe, expect, it } from 'vitest';
+import { describe, expect, it } from 'vitest';
-import type { ISheetData } from '../../../../basics/common';
-import { ErrorType } from '../../../../basics/error-type';
-import { RangeReferenceObject } from '../../../../engine/reference-object/range-reference-object';
-import type { ArrayValueObject } from '../../../../engine/value-object/array-value-object';
-import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
import { FUNCTION_NAMES_MATH } from '../../function-names';
import { Acos } from '..';
+import { NumberValueObject } from '../../../../engine/value-object/primitive-object';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
-const cellData = {
- 0: {
- 0: {
- v: 1,
- },
- 1: {
- v: ' ',
- },
- 2: {
- v: 1.23,
- },
- 3: {
- v: true,
- },
- 4: {
- v: false,
- },
- },
- 1: {
- 0: {
- v: 0,
- },
- 1: {
- v: '100',
- },
- 2: {
- v: '2.34',
- },
- 3: {
- v: 'test',
- },
- 4: {
- v: -3,
- },
- },
-};
+describe('Test acos function', () => {
+ const textFunction = new Acos(FUNCTION_NAMES_MATH.ACOS);
-describe('test acos', () => {
- let unitId: string;
- let sheetId: string;
- let sheetData: ISheetData = {};
- let acos: Acos;
- let acosCalculate: (range: IRange) => ArrayValueObject;
-
- beforeEach(() => {
- unitId = 'test';
- sheetId = 'sheet1';
- sheetData = {
- [sheetId]: {
- cellData: new ObjectMatrix(cellData),
- rowCount: 4,
- columnCount: 3,
- },
- };
-
- // register acos
- acos = new Acos(FUNCTION_NAMES_MATH.ACOS);
- acosCalculate = (range: IRange) => {
- // range
-
- const rangeRef = new RangeReferenceObject(range, sheetId, unitId);
- rangeRef.setUnitData({
- [unitId]: sheetData,
- });
-
- return acos.calculate(rangeRef) as ArrayValueObject;
- };
- });
-
- describe('acos', () => {
- describe('correct situations', () => {
- it('single cell', async () => {
- // cell A1
- const cell = {
- startRow: 0,
- startColumn: 0,
- endRow: 0,
- endColumn: 0,
- };
-
- const arrayValue = acosCalculate(cell);
- expect(arrayValue.getFirstCell().getValue()).toBe(0);
- });
- it('range', async () => {
- // cell A1:E2
- const cell = {
- startRow: 0,
- startColumn: 0,
- endRow: 1,
- endColumn: 4,
- };
-
- const arrayValue = acosCalculate(cell);
- expect(arrayValue.toValue()).toStrictEqual([
- [0, '#VALUE!', '#NUM!', 0, 1.5707963267948966],
- [1.5707963267948966, '#NUM!', '#NUM!', '#VALUE!', '#NUM!'],
- ]);
- });
+ describe('Acos', () => {
+ it('Value is normal', () => {
+ const value = new NumberValueObject(1);
+ const result = textFunction.calculate(value);
+ expect(result.getValue()).toBe(0);
});
- describe('fault situations', () => {
- it('value error', async () => {
- const error = new ErrorValueObject(ErrorType.VALUE);
- const errorValue = acos.calculate(error);
- expect(errorValue.isError()).toBeTruthy();
+ it('Value is array', () => {
+ const valueArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [1, ' ', 1.23, true, false],
+ [0, '100', '2.34', 'test', -3],
+ ]),
+ rowCount: 2,
+ columnCount: 5,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
});
+ const result = textFunction.calculate(valueArray);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[0, '#VALUE!', '#NUM!', 0, 1.5707963267948966],
+ [1.5707963267948966, '#NUM!', '#NUM!', '#VALUE!', '#NUM!']]);
});
});
});
diff --git a/packages/engine-formula/src/functions/math/acos/index.ts b/packages/engine-formula/src/functions/math/acos/index.ts
index 1709f28dd7..0fb9692575 100644
--- a/packages/engine-formula/src/functions/math/acos/index.ts
+++ b/packages/engine-formula/src/functions/math/acos/index.ts
@@ -15,20 +15,20 @@
*/
import { ErrorType } from '../../../basics/error-type';
-import type { BaseReferenceObject, FunctionVariantType } from '../../../engine/reference-object/base-reference-object';
import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { BaseFunction } from '../../base-function';
export class Acos extends BaseFunction {
- override calculate(variant: FunctionVariantType) {
- if (variant.isError()) {
- return new ErrorValueObject(ErrorType.VALUE);
+ override calculate(variant: BaseValueObject) {
+ if (variant == null) {
+ return new ErrorValueObject(ErrorType.NA);
}
- if (variant.isReferenceObject()) {
- variant = (variant as BaseReferenceObject).toArrayValueObject();
+ if (variant.isError()) {
+ return variant;
}
- return (variant as BaseValueObject).acos();
+
+ return variant.acos();
}
}
diff --git a/packages/engine-formula/src/functions/math/acosh/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/acosh/__tests__/index.spec.ts
index 9e03c15a26..508ccdc609 100644
--- a/packages/engine-formula/src/functions/math/acosh/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/acosh/__tests__/index.spec.ts
@@ -14,124 +14,39 @@
* limitations under the License.
*/
-import type { IRange } from '@univerjs/core';
-import { ObjectMatrix } from '@univerjs/core';
-import { beforeEach, describe, expect, it } from 'vitest';
+import { describe, expect, it } from 'vitest';
-import type { ISheetData } from '../../../../basics/common';
-import { ErrorType } from '../../../../basics/error-type';
-import { RangeReferenceObject } from '../../../../engine/reference-object/range-reference-object';
-import type { ArrayValueObject } from '../../../../engine/value-object/array-value-object';
-import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
import { FUNCTION_NAMES_MATH } from '../../function-names';
import { Acosh } from '..';
+import { NumberValueObject } from '../../../../engine/value-object/primitive-object';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
-const cellData = {
- 0: {
- 0: {
- v: 1,
- },
- 1: {
- v: ' ',
- },
- 2: {
- v: 1.23,
- },
- 3: {
- v: true,
- },
- 4: {
- v: false,
- },
- },
- 1: {
- 0: {
- v: 0,
- },
- 1: {
- v: '100',
- },
- 2: {
- v: '2.34',
- },
- 3: {
- v: 'test',
- },
- 4: {
- v: -3,
- },
- },
-};
+describe('Test acosh function', () => {
+ const textFunction = new Acosh(FUNCTION_NAMES_MATH.ACOSH);
-describe('test acosh', () => {
- let unitId: string;
- let sheetId: string;
- let sheetData: ISheetData = {};
- let acosh: Acosh;
- let acoshCalculate: (range: IRange) => ArrayValueObject;
-
- beforeEach(() => {
- unitId = 'test';
- sheetId = 'sheet1';
- sheetData = {
- [sheetId]: {
- cellData: new ObjectMatrix(cellData),
- rowCount: 4,
- columnCount: 3,
- },
- };
-
- // register acosh
- acosh = new Acosh(FUNCTION_NAMES_MATH.ACOSH);
- acoshCalculate = (range: IRange) => {
- // range
-
- const rangeRef = new RangeReferenceObject(range, sheetId, unitId);
- rangeRef.setUnitData({
- [unitId]: sheetData,
- });
-
- return acosh.calculate(rangeRef) as ArrayValueObject;
- };
- });
-
- describe('acosh', () => {
- describe('correct situations', () => {
- it('single cell', async () => {
- // cell A1
- const cell = {
- startRow: 0,
- startColumn: 0,
- endRow: 0,
- endColumn: 0,
- };
-
- const arrayValue = acoshCalculate(cell);
- expect(arrayValue.getFirstCell().getValue()).toBe(0);
- });
- it('range', async () => {
- // cell A1:E2
- const cell = {
- startRow: 0,
- startColumn: 0,
- endRow: 1,
- endColumn: 4,
- };
-
- const arrayValue = acoshCalculate(cell);
- expect(arrayValue.toValue()).toStrictEqual([
- [0, '#VALUE!', 0.6658635291565548, 0, '#NUM!'],
- ['#NUM!', 5.298292365610484, 1.494153066724473, '#VALUE!', '#NUM!'],
- ]);
- });
+ describe('Acosh', () => {
+ it('Value is normal', () => {
+ const value = new NumberValueObject(1);
+ const result = textFunction.calculate(value);
+ expect(result.getValue()).toBe(0);
});
- describe('fault situations', () => {
- it('value error', async () => {
- const error = new ErrorValueObject(ErrorType.VALUE);
- const errorValue = acosh.calculate(error);
- expect(errorValue.isError()).toBeTruthy();
+ it('Value is array', () => {
+ const valueArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [1, ' ', 1.23, true, false],
+ [0, '100', '2.34', 'test', -3],
+ ]),
+ rowCount: 2,
+ columnCount: 5,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
});
+ const result = textFunction.calculate(valueArray);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[0, '#VALUE!', 0.6658635291565548, 0, '#NUM!'],
+ ['#NUM!', 5.298292365610484, 1.494153066724473, '#VALUE!', '#NUM!']]);
});
});
});
diff --git a/packages/engine-formula/src/functions/math/acosh/index.ts b/packages/engine-formula/src/functions/math/acosh/index.ts
index 9c5ad0799f..73f8bc57c1 100644
--- a/packages/engine-formula/src/functions/math/acosh/index.ts
+++ b/packages/engine-formula/src/functions/math/acosh/index.ts
@@ -15,20 +15,19 @@
*/
import { ErrorType } from '../../../basics/error-type';
-import type { BaseReferenceObject, FunctionVariantType } from '../../../engine/reference-object/base-reference-object';
import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { BaseFunction } from '../../base-function';
export class Acosh extends BaseFunction {
- override calculate(variant: FunctionVariantType) {
- if (variant.isError()) {
- return new ErrorValueObject(ErrorType.VALUE);
+ override calculate(variant: BaseValueObject) {
+ if (variant == null) {
+ return new ErrorValueObject(ErrorType.NA);
}
- if (variant.isReferenceObject()) {
- variant = (variant as BaseReferenceObject).toArrayValueObject();
+ if (variant.isError()) {
+ return new ErrorValueObject(ErrorType.VALUE);
}
- return (variant as BaseValueObject).acosh();
+ return variant.acosh();
}
}
diff --git a/packages/engine-formula/src/functions/math/acot/__tests__/index.spec.ts b/packages/engine-formula/src/functions/math/acot/__tests__/index.spec.ts
index fdbb69d9d0..55f02ea1c1 100644
--- a/packages/engine-formula/src/functions/math/acot/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/math/acot/__tests__/index.spec.ts
@@ -14,126 +14,39 @@
* limitations under the License.
*/
-import type { IRange } from '@univerjs/core';
-import { ObjectMatrix } from '@univerjs/core';
-import { beforeEach, describe, expect, it } from 'vitest';
+import { describe, expect, it } from 'vitest';
-import type { ISheetData } from '../../../../basics/common';
-import { ErrorType } from '../../../../basics/error-type';
-import { RangeReferenceObject } from '../../../../engine/reference-object/range-reference-object';
-import type { ArrayValueObject } from '../../../../engine/value-object/array-value-object';
-import { ErrorValueObject } from '../../../../engine/value-object/base-value-object';
import { FUNCTION_NAMES_MATH } from '../../function-names';
import { Acot } from '..';
+import { NumberValueObject } from '../../../../engine/value-object/primitive-object';
+import { ArrayValueObject, transformToValue, transformToValueObject } from '../../../../engine/value-object/array-value-object';
-const cellData = {
- 0: {
- 0: {
- v: 1,
- },
- 1: {
- v: ' ',
- },
- 2: {
- v: 1.23,
- },
- 3: {
- v: true,
- },
- 4: {
- v: false,
- },
- },
- 1: {
- 0: {
- v: 0,
- },
- 1: {
- v: '100',
- },
- 2: {
- v: '2.34',
- },
- 3: {
- v: 'test',
- },
- 4: {
- v: -3,
- },
- },
-};
+describe('Test acot function', () => {
+ const textFunction = new Acot(FUNCTION_NAMES_MATH.ACOT);
-describe('test acot', () => {
- let unitId: string;
- let sheetId: string;
- let sheetData: ISheetData = {};
- let acot: Acot;
- let acotCalculate: (range: IRange) => ArrayValueObject;
-
- beforeEach(() => {
- unitId = 'test';
- sheetId = 'sheet1';
- sheetData = {
- [sheetId]: {
- cellData: new ObjectMatrix(cellData),
- rowCount: 4,
- columnCount: 3,
- },
- };
-
- // register acot
- acot = new Acot(FUNCTION_NAMES_MATH.ACOT);
- acotCalculate = (range: IRange) => {
- // range
-
- const rangeRef = new RangeReferenceObject(range, sheetId, unitId);
- rangeRef.setUnitData({
- [unitId]: sheetData,
- });
-
- return acot.calculate(rangeRef) as ArrayValueObject;
- };
- });
-
- describe('acot', () => {
- describe('correct situations', () => {
- it('single cell', async () => {
- // cell A1
- const cell = {
- startRow: 0,
- startColumn: 0,
- endRow: 0,
- endColumn: 0,
- };
-
- const arrayValue = acotCalculate(cell);
- expect(arrayValue.getFirstCell().getValue()).toBe(0.7853981633974483);
- });
- it('range', async () => {
- // cell A1:E2
- const cell = {
- startRow: 0,
- startColumn: 0,
- endRow: 1,
- endColumn: 4,
- };
-
- const arrayValue = acotCalculate(cell);
-
- // =ACOT(-3) google gets -0.3217505544, but excel gets 2.819842
- expect(arrayValue.toValue()).toStrictEqual([
- [0.7853981633974483, '#VALUE!', 0.682622552417217, 0.7853981633974483, 1.5707963267948966],
- [1.5707963267948966, 0.009999666686665238, 0.40385979490737667, '#VALUE!', -0.3217505543966422],
- ]);
- });
+ describe('Acot', () => {
+ it('Value is normal', () => {
+ const value = new NumberValueObject(1);
+ const result = textFunction.calculate(value);
+ expect(result.getValue()).toBe(0.7853981633974483);
});
- describe('fault situations', () => {
- it('value error', async () => {
- const error = new ErrorValueObject(ErrorType.VALUE);
- const errorValue = acot.calculate(error);
- expect(errorValue.isError()).toBeTruthy();
+ it('Value is array', () => {
+ const valueArray = new ArrayValueObject({
+ calculateValueList: transformToValueObject([
+ [1, ' ', 1.23, true, false],
+ [0, '100', '2.34', 'test', -3],
+ ]),
+ rowCount: 2,
+ columnCount: 5,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
});
+ const result = textFunction.calculate(valueArray);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([[0.7853981633974483, '#VALUE!', 0.682622552417217, 0.7853981633974483, 1.5707963267948966],
+ [1.5707963267948966, 0.009999666686665238, 0.40385979490737667, '#VALUE!', -0.3217505543966422]]);
});
});
});
diff --git a/packages/engine-formula/src/functions/math/acot/index.ts b/packages/engine-formula/src/functions/math/acot/index.ts
index 98cd6be8fd..74bc2decc2 100644
--- a/packages/engine-formula/src/functions/math/acot/index.ts
+++ b/packages/engine-formula/src/functions/math/acot/index.ts
@@ -15,20 +15,19 @@
*/
import { ErrorType } from '../../../basics/error-type';
-import type { BaseReferenceObject, FunctionVariantType } from '../../../engine/reference-object/base-reference-object';
import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
export class Acot extends BaseFunction {
- override calculate(variant: FunctionVariantType) {
- if (variant.isError()) {
- return new ErrorValueObject(ErrorType.VALUE);
+ override calculate(variant: BaseValueObject) {
+ if (variant == null) {
+ return new ErrorValueObject(ErrorType.NA);
}
- if (variant.isReferenceObject()) {
- variant = (variant as BaseReferenceObject).toArrayValueObject();
+ if (variant.isError()) {
+ return variant;
}
if ((variant as BaseValueObject).isArray()) {
diff --git a/packages/engine-formula/src/functions/math/sum/index.ts b/packages/engine-formula/src/functions/math/sum/index.ts
index 95e24404c5..027ecd7a32 100644
--- a/packages/engine-formula/src/functions/math/sum/index.ts
+++ b/packages/engine-formula/src/functions/math/sum/index.ts
@@ -21,6 +21,10 @@ import { BaseFunction } from '../../base-function';
export class Sum extends BaseFunction {
override calculate(...variants: BaseValueObject[]) {
+ if (variants.length === 0) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
let accumulatorAll: BaseValueObject = new NumberValueObject(0);
for (let i = 0; i < variants.length; i++) {
let variant = variants[i];
diff --git a/packages/engine-formula/src/functions/math/sumif/index.ts b/packages/engine-formula/src/functions/math/sumif/index.ts
index a8635c9a94..69b9d2382d 100644
--- a/packages/engine-formula/src/functions/math/sumif/index.ts
+++ b/packages/engine-formula/src/functions/math/sumif/index.ts
@@ -22,6 +22,10 @@ import { BaseFunction } from '../../base-function';
export class Sumif extends BaseFunction {
override calculate(range: BaseValueObject, criteria: BaseValueObject, sumRange?: BaseValueObject) {
+ if (range == null || criteria == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
if (range.isError() || criteria.isError() || sumRange?.isError()) {
return new ErrorValueObject(ErrorType.NA);
}
diff --git a/packages/engine-formula/src/functions/math/sumifs/index.ts b/packages/engine-formula/src/functions/math/sumifs/index.ts
index b48b3cf532..a4bf3a5020 100644
--- a/packages/engine-formula/src/functions/math/sumifs/index.ts
+++ b/packages/engine-formula/src/functions/math/sumifs/index.ts
@@ -24,6 +24,14 @@ import { BaseFunction } from '../../base-function';
export class Sumifs extends BaseFunction {
override calculate(sumRange: BaseValueObject, ...variants: BaseValueObject[]) {
+ if (sumRange == null) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
+ if (variants.length < 2) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
if (sumRange.isError()) {
return new ErrorValueObject(ErrorType.NA);
}
diff --git a/packages/engine-formula/src/functions/statistical/average/index.ts b/packages/engine-formula/src/functions/statistical/average/index.ts
index cde9ba4b38..184e006df4 100644
--- a/packages/engine-formula/src/functions/statistical/average/index.ts
+++ b/packages/engine-formula/src/functions/statistical/average/index.ts
@@ -14,12 +14,17 @@
* limitations under the License.
*/
-import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { ErrorType } from '../../../basics/error-type';
+import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
export class Average extends BaseFunction {
override calculate(...variants: BaseValueObject[]) {
+ if (variants.length === 0) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
let accumulatorSum: BaseValueObject = new NumberValueObject(0);
let accumulatorCount: BaseValueObject = new NumberValueObject(0);
for (let i = 0; i < variants.length; i++) {
diff --git a/packages/engine-formula/src/functions/statistical/count/index.ts b/packages/engine-formula/src/functions/statistical/count/index.ts
index 4a6671edeb..94779cdd5d 100644
--- a/packages/engine-formula/src/functions/statistical/count/index.ts
+++ b/packages/engine-formula/src/functions/statistical/count/index.ts
@@ -14,12 +14,17 @@
* limitations under the License.
*/
-import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { ErrorType } from '../../../basics/error-type';
+import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
export class Count extends BaseFunction {
override calculate(...variants: BaseValueObject[]) {
+ if (variants.length === 0) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
let accumulatorAll: BaseValueObject = new NumberValueObject(0);
for (let i = 0; i < variants.length; i++) {
let variant = variants[i];
diff --git a/packages/engine-formula/src/functions/statistical/counta/index.ts b/packages/engine-formula/src/functions/statistical/counta/index.ts
index 87b5812206..5286262337 100644
--- a/packages/engine-formula/src/functions/statistical/counta/index.ts
+++ b/packages/engine-formula/src/functions/statistical/counta/index.ts
@@ -14,12 +14,17 @@
* limitations under the License.
*/
-import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { ErrorType } from '../../../basics/error-type';
+import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
export class CountA extends BaseFunction {
override calculate(...variants: BaseValueObject[]) {
+ if (variants.length === 0) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
let accumulatorAll: BaseValueObject = new NumberValueObject(0);
for (let i = 0; i < variants.length; i++) {
let variant = variants[i];
diff --git a/packages/engine-formula/src/functions/statistical/max/index.ts b/packages/engine-formula/src/functions/statistical/max/index.ts
index b9be702f05..ddd7ad7096 100644
--- a/packages/engine-formula/src/functions/statistical/max/index.ts
+++ b/packages/engine-formula/src/functions/statistical/max/index.ts
@@ -14,12 +14,17 @@
* limitations under the License.
*/
-import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { ErrorType } from '../../../basics/error-type';
+import { type BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
export class Max extends BaseFunction {
override calculate(...variants: BaseValueObject[]) {
+ if (variants.length === 0) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
let accumulatorAll: BaseValueObject = new NumberValueObject(Number.NEGATIVE_INFINITY);
for (let i = 0; i < variants.length; i++) {
let variant = variants[i];
diff --git a/packages/engine-formula/src/functions/statistical/min/index.ts b/packages/engine-formula/src/functions/statistical/min/index.ts
index ecfabb0d67..58d39e4102 100644
--- a/packages/engine-formula/src/functions/statistical/min/index.ts
+++ b/packages/engine-formula/src/functions/statistical/min/index.ts
@@ -14,12 +14,18 @@
* limitations under the License.
*/
-import type { BaseValueObject, ErrorValueObject } from '../../../engine/value-object/base-value-object';
+import { ErrorType } from '../../../basics/error-type';
+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
+import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
import { NumberValueObject } from '../../../engine/value-object/primitive-object';
import { BaseFunction } from '../../base-function';
export class Min extends BaseFunction {
override calculate(...variants: BaseValueObject[]) {
+ if (variants.length === 0) {
+ return new ErrorValueObject(ErrorType.NA);
+ }
+
let accumulatorAll: BaseValueObject = new NumberValueObject(Number.POSITIVE_INFINITY);
for (let i = 0; i < variants.length; i++) {
let variant = variants[i];
diff --git a/packages/engine-formula/src/functions/text/concatenate/__tests__/index.spec.ts b/packages/engine-formula/src/functions/text/concatenate/__tests__/index.spec.ts
index e914258453..5bc089e771 100644
--- a/packages/engine-formula/src/functions/text/concatenate/__tests__/index.spec.ts
+++ b/packages/engine-formula/src/functions/text/concatenate/__tests__/index.spec.ts
@@ -109,7 +109,7 @@ describe('Test concatenate function', () => {
const text1 = new ArrayValueObject({
calculateValueList: transformToValueObject([
['a', 'd'],
- ['b', 'e'],
+ [0, null],
]),
rowCount: 2,
columnCount: 2,
@@ -121,7 +121,7 @@ describe('Test concatenate function', () => {
const text2 = new ArrayValueObject({
calculateValueList: transformToValueObject([
[1, 2, 3],
- [2, 3, 4],
+ [0, null, 4],
[3, 4, 5],
]),
rowCount: 3,
@@ -132,7 +132,7 @@ describe('Test concatenate function', () => {
column: 0,
});
const result = textFunction.calculate(text1, text2);
- expect(transformToValue(result.getArrayValue())).toStrictEqual([['a1', 'd2', '#N/A'], ['b2', 'e3', '#N/A'], ['#N/A', '#N/A', '#N/A']]);
+ expect(transformToValue(result.getArrayValue())).toStrictEqual([['a1', 'd2', '#N/A'], ['00', '', '#N/A'], ['#N/A', '#N/A', '#N/A']]);
});
});
});
diff --git a/packages/engine-formula/src/functions/text/concatenate/index.ts b/packages/engine-formula/src/functions/text/concatenate/index.ts
index a86497b5b2..3ccdb52e3d 100644
--- a/packages/engine-formula/src/functions/text/concatenate/index.ts
+++ b/packages/engine-formula/src/functions/text/concatenate/index.ts
@@ -57,7 +57,10 @@ export class Concatenate extends BaseFunction {
return textValueObject;
}
- return new StringValueObject(`${resultValueObject?.getValue() || ''}${textValueObject.getValue()}`);
+ const resultValueObjectString = resultValueObject?.isNull() ? '' : resultValueObject?.getValue() ?? '';
+ const textValueObjectString = textValueObject?.isNull() ? '' : textValueObject?.getValue() ?? '';
+
+ return new StringValueObject(`${resultValueObjectString}${textValueObjectString}`);
});
}
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index 02cf4516de..6f741e3992 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -26,6 +26,7 @@ export type {
ISheetData,
IUnitData,
IUnitSheetNameMap,
+ INumfmtItemMap,
} from './basics/common';
export { isInDirtyRange } from './basics/dirty';
export { ErrorType } from './basics/error-type';
@@ -134,3 +135,5 @@ export { IFunctionService } from './services/function.service';
export { type IOtherFormulaManagerService, OtherFormulaManagerService } from './services/other-formula-manager.service';
export { FormulaExecuteStageType, type IExecutionInProgressParams } from './services/runtime.service';
export { FormulaExecutedStateType, type IAllRuntimeData } from './services/runtime.service';
+export { SetNumfmtFormulaDataMutation } from './commands/mutations/set-numfmt-formula-data.mutation';
+export type { ISetNumfmtFormulaDataMutationParams } from './commands/mutations/set-numfmt-formula-data.mutation';
diff --git a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
index e9cb107a51..ba1dbcad2f 100644
--- a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
+++ b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts
@@ -350,6 +350,91 @@ describe('Test formula data model', () => {
expect(formulaData).toStrictEqual(result);
});
});
+
+ describe('updateNumfmtData', () => {
+ it('update numfmt data', () => {
+ const unitId = 'test';
+ const sheetId = 'sheet1';
+
+ formulaDataModel.setNumfmtItemMap({
+ [unitId]: {
+ [sheetId]: {
+ 0: {
+ 3: '0.00',
+ },
+ },
+ },
+ });
+
+ const cellValue = {
+ 0: {
+ 3: {
+ v: null,
+ p: null,
+ f: null,
+ si: null,
+ },
+ },
+ };
+
+ const result = {
+ [unitId]: {
+ [sheetId]: {
+ 0: {
+ 3: null,
+ },
+ },
+ },
+ };
+
+ formulaDataModel.updateNumfmtData(unitId, sheetId, cellValue);
+
+ const numfmtData = formulaDataModel.getNumfmtItemMap();
+ expect(numfmtData).toStrictEqual(result);
+ });
+ });
+
+ describe('updateNumfmtMap', () => {
+ it('update numfmt map data', () => {
+ const unitId = 'test';
+ const sheetId = 'sheet1';
+
+ formulaDataModel.setNumfmtItemMap({
+ [unitId]: {
+ [sheetId]: {
+ 0: {
+ 3: '0.00',
+ },
+ },
+ },
+ });
+
+ const numfmtItemMap = {
+ [unitId]: {
+ [sheetId]: {
+ 0: {
+ 3: null,
+ },
+ },
+ },
+ };
+
+ const result = {
+ [unitId]: {
+ [sheetId]: {
+ 0: {
+ 3: null,
+ },
+ },
+ },
+ };
+
+ formulaDataModel.updateNumfmtItemMap(numfmtItemMap);
+
+ const numfmtData = formulaDataModel.getNumfmtItemMap();
+ expect(numfmtData).toStrictEqual(result);
+ });
+ });
});
describe('function initSheetFormulaData', () => {
diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.ts
index b549e78ad2..62d3a9085e 100644
--- a/packages/engine-formula/src/models/formula-data.model.ts
+++ b/packages/engine-formula/src/models/formula-data.model.ts
@@ -23,6 +23,7 @@ import type {
IArrayFormulaUnitCellType,
IFormulaData,
IFormulaDataItem,
+ INumfmtItemMap,
IRuntimeUnitDataType,
ISheetData,
IUnitData,
@@ -43,6 +44,9 @@ export class FormulaDataModel extends Disposable {
private _arrayFormulaCellData: IArrayFormulaUnitCellType = {};
+ // TODO@Dushusir: Determine the node.js environment and synchronize to the resource plugin when SSC is used
+ private _numfmtItemMap: INumfmtItemMap = {};
+
constructor(
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder
@@ -161,20 +165,63 @@ export class FormulaDataModel extends Disposable {
this._formulaData = value;
}
+ getArrayFormulaRange(): IArrayFormulaRangeType {
+ return this._arrayFormulaRange;
+ }
+
setArrayFormulaRange(value: IArrayFormulaRangeType) {
this._arrayFormulaRange = value;
}
- getArrayFormulaRange(): IArrayFormulaRangeType {
- return this._arrayFormulaRange;
+ getArrayFormulaCellData() {
+ return this._arrayFormulaCellData;
}
setArrayFormulaCellData(value: IArrayFormulaUnitCellType) {
this._arrayFormulaCellData = value;
}
- getArrayFormulaCellData() {
- return this._arrayFormulaCellData;
+ getNumfmtItemMap() {
+ return this._numfmtItemMap;
+ }
+
+ getNumfmtValue(unitId: string, sheetId: string, row: number, column: number) {
+ return this._numfmtItemMap[unitId]?.[sheetId]?.[row]?.[column];
+ }
+
+ setNumfmtItemMap(value: INumfmtItemMap) {
+ this._numfmtItemMap = value;
+ }
+
+ updateNumfmtItemMap(value: INumfmtItemMap) {
+ Object.keys(value).forEach((unitId) => {
+ const sheetData = value[unitId];
+
+ if (sheetData == null) {
+ return true;
+ }
+
+ if (this._numfmtItemMap[unitId] == null) {
+ this._numfmtItemMap[unitId] = {};
+ }
+
+ Object.keys(sheetData).forEach((sheetId) => {
+ const numfmtItemMap = sheetData[sheetId];
+ const numfmtItemMatrix = new ObjectMatrix(numfmtItemMap);
+
+ if (this._numfmtItemMap[unitId]![sheetId] == null) {
+ this._numfmtItemMap[unitId]![sheetId] = {};
+ }
+
+ numfmtItemMatrix.forValue((r, c, numfmtItem) => {
+ if (this._numfmtItemMap[unitId]![sheetId][r] == null) {
+ this._numfmtItemMap[unitId]![sheetId][r] = {};
+ }
+
+ this._numfmtItemMap[unitId]![sheetId][r][c] = numfmtItem;
+ });
+ });
+ });
}
mergeArrayFormulaRange(formulaData: IArrayFormulaRangeType) {
@@ -450,6 +497,46 @@ export class FormulaDataModel extends Disposable {
});
}
+ updateNumfmtData(
+ unitId: string,
+ sheetId: string,
+ cellValue: IObjectMatrixPrimitiveType<Nullable<ICellData>>
+ ) {
+ // remove the array formula range when cell value is null
+
+ const arrayFormulaRange = this._arrayFormulaRange[unitId]?.[sheetId];
+ const arrayFormulaRangeMatrix = new ObjectMatrix(arrayFormulaRange);
+
+ const numfmtData = this._numfmtItemMap[unitId]?.[sheetId];
+
+ if (!numfmtData) return;
+
+ const numfmtDataMatrix = new ObjectMatrix(numfmtData);
+
+ const cellMatrix = new ObjectMatrix(cellValue);
+ cellMatrix.forValue((r, c, cell) => {
+ const formulaString = cell?.f || '';
+ const formulaId = cell?.si || '';
+
+ const checkFormulaString = isFormulaString(formulaString);
+ const checkFormulaId = isFormulaId(formulaId);
+
+ if (!checkFormulaString && !checkFormulaId) {
+ numfmtDataMatrix.setValue(r, c, null);
+
+ const arrayFormulaRangeValue = arrayFormulaRangeMatrix.getValue(r, c);
+ if (arrayFormulaRangeValue) {
+ const { startRow, startColumn, endRow, endColumn } = arrayFormulaRangeValue;
+ for (let row = startRow; row <= endRow; row++) {
+ for (let column = startColumn; column <= endColumn; column++) {
+ numfmtDataMatrix.setValue(row, column, null);
+ }
+ }
+ }
+ }
+ });
+ }
+
getFormulaItemBySId(sId: string, sheetId: string, unitId: string): Nullable<IFormulaDataItem> {
const formulaData = this._formulaData;
if (formulaData[unitId] == null) {
diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.ts
index 74d35de7c7..272db4207c 100644
--- a/packages/engine-formula/src/services/current-data.service.ts
+++ b/packages/engine-formula/src/services/current-data.service.ts
@@ -23,6 +23,7 @@ import type {
IDirtyUnitSheetNameMap,
IFormulaData,
IFormulaDatasetConfig,
+ INumfmtItemMap,
IRuntimeUnitDataType,
ISheetData,
IUnitData,
@@ -78,6 +79,8 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
private _dirtyNameMap: IDirtyUnitSheetNameMap = {};
+ private _numfmtItemMap: INumfmtItemMap = {};
+
private _dirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};
private _excludedCell: Nullable<IUnitExcludedCell>;
@@ -93,6 +96,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
this._sheetNameMap = {};
this._dirtyRanges = [];
this._dirtyNameMap = {};
+ this._numfmtItemMap = {};
this._dirtyUnitFeatureMap = {};
this._excludedCell = {};
}
@@ -129,6 +133,10 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
return this._dirtyNameMap;
}
+ getNumfmtItemMap() {
+ return this._numfmtItemMap;
+ }
+
getDirtyUnitFeatureMap() {
return this._dirtyUnitFeatureMap;
}
@@ -155,6 +163,8 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
this._dirtyNameMap = config.dirtyNameMap;
+ this._numfmtItemMap = config.numfmtItemMap;
+
this._dirtyUnitFeatureMap = config.dirtyUnitFeatureMap;
this._excludedCell = config.excludedCell;
diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.ts
index f4e4bb37bf..8b0c89c48b 100644
--- a/packages/engine-formula/src/services/runtime.service.ts
+++ b/packages/engine-formula/src/services/runtime.service.ts
@@ -15,12 +15,13 @@
*/
import type { ICellData, IRange, Nullable } from '@univerjs/core';
-import { CellValueType, Disposable, isNullCell, ObjectMatrix } from '@univerjs/core';
+import { CellValueType, Disposable, isNullCell, isRealNum, ObjectMatrix } from '@univerjs/core';
import { createIdentifier } from '@wendellhu/redi';
import type {
IArrayFormulaRangeType,
IFeatureDirtyRangeType,
+ INumfmtItemMap,
IRuntimeOtherUnitDataType,
IRuntimeUnitDataType,
} from '../basics/common';
@@ -66,6 +67,7 @@ export interface IAllRuntimeData {
functionsExecutedState: FormulaExecutedStateType;
arrayFormulaCellData: IRuntimeUnitDataType;
clearArrayFormulaCellData: IRuntimeUnitDataType;
+ numfmtItemMap: INumfmtItemMap;
runtimeFeatureRange: { [featureId: string]: IFeatureDirtyRangeType };
runtimeFeatureCellData: { [featureId: string]: IRuntimeUnitDataType };
@@ -194,6 +196,8 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
private _runtimeClearArrayFormulaCellData: IRuntimeUnitDataType = {};
+ private _numfmtItemMap: INumfmtItemMap = {};
+
private _runtimeFeatureRange: { [featureId: string]: IFeatureDirtyRangeType } = {};
private _runtimeFeatureCellData: { [featureId: string]: IRuntimeUnitDataType } = {};
@@ -330,6 +334,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
this._runtimeData = {};
this._runtimeOtherData = {};
this._unitArrayFormulaRange = {};
+ this._numfmtItemMap = {};
this._runtimeArrayFormulaCellData = {};
this._runtimeClearArrayFormulaCellData = {};
@@ -407,6 +412,16 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
this._unitArrayFormulaRange[unitId] = {};
}
+ if (this._numfmtItemMap[unitId] == null) {
+ this._numfmtItemMap[unitId] = {};
+ }
+
+ if (this._numfmtItemMap[unitId]![sheetId] == null) {
+ this._numfmtItemMap[unitId]![sheetId] = {};
+ }
+
+ const numfmtItem = this._numfmtItemMap[unitId]![sheetId];
+
const arrayFormulaRange = this._unitArrayFormulaRange[unitId]!;
let arrayData = new ObjectMatrix<IRange>();
@@ -454,9 +469,17 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
* then it is not treated as an array range and is directly assigned.
*/
if (startRow === endRow && startColumn === endColumn) {
- const valueObject = this._objectValueToCellValue(objectValueRefOrArray.getFirstCell());
+ const firstCell = objectValueRefOrArray.getFirstCell();
+ const valueObject = this._objectValueToCellValue(firstCell);
sheetData.setValue(row, column, valueObject);
clearArrayUnitData.setValue(row, column, valueObject);
+
+ if (numfmtItem[row] == null) {
+ numfmtItem[row] = {};
+ }
+
+ numfmtItem[row]![column] = firstCell.getPattern();
+
return;
}
@@ -494,12 +517,32 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
}
sheetData.setValue(row, column, { ...value });
}
- arrayUnitData.setValue(rowIndex - startRow + row, columnIndex - startColumn + column, value);
+
+ const currentRow = rowIndex - startRow + row;
+ const currentColumn = columnIndex - startColumn + column;
+
+ arrayUnitData.setValue(currentRow, currentColumn, value);
+
+ const pattern = valueObject?.getPattern();
+ if (pattern) {
+ if (numfmtItem[currentRow] == null) {
+ numfmtItem[currentRow] = {};
+ }
+
+ numfmtItem[currentRow]![currentColumn] = pattern;
+ }
});
}
} else {
const valueObject = this._objectValueToCellValue(functionVariant as BaseValueObject);
sheetData.setValue(row, column, valueObject);
+
+ if (numfmtItem[row] == null) {
+ numfmtItem[row] = {};
+ }
+
+ numfmtItem[row]![column] = functionVariant.getPattern();
+
clearArrayUnitData.setValue(row, column, valueObject);
}
}
@@ -512,6 +555,10 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
return this._unitArrayFormulaRange;
}
+ getNumfmtItemMap() {
+ return this._numfmtItemMap;
+ }
+
getRuntimeOtherData() {
return this._runtimeOtherData;
}
@@ -548,6 +595,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
functionsExecutedState: this._functionsExecutedState,
arrayFormulaCellData: this.getRuntimeArrayFormulaCellData(),
clearArrayFormulaCellData: this.getRuntimeClearArrayFormulaCellData(),
+ numfmtItemMap: this.getNumfmtItemMap(),
runtimeFeatureRange: this.getRuntimeFeatureRange(),
runtimeFeatureCellData: this.getRuntimeFeatureCellData(),
@@ -596,6 +644,13 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
t: CellValueType.BOOLEAN,
};
}
+ // String "00"
+ if (vo.isString() && isRealNum(v as string)) {
+ return {
+ v,
+ t: CellValueType.FORCE_STRING,
+ };
+ }
return {
v,
t: CellValueType.STRING,
diff --git a/packages/sheets-formula/package.json b/packages/sheets-formula/package.json
index 0e036fe4e0..2d0955cd9d 100644
--- a/packages/sheets-formula/package.json
+++ b/packages/sheets-formula/package.json
@@ -53,6 +53,7 @@
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/sheets": "workspace:*",
+ "@univerjs/sheets-numfmt": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
"@univerjs/ui": "workspace:*",
"@wendellhu/redi": "^0.13.0",
@@ -71,6 +72,7 @@
"@univerjs/engine-render": "workspace:*",
"@univerjs/shared": "workspace:*",
"@univerjs/sheets": "workspace:*",
+ "@univerjs/sheets-numfmt": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
"@univerjs/ui": "workspace:*",
"@vitejs/plugin-react": "^4.2.1",
diff --git a/packages/sheets-formula/src/controllers/array-formula-display.controller.ts b/packages/sheets-formula/src/controllers/array-formula-display.controller.ts
index 1d96918e03..90b6dc022d 100644
--- a/packages/sheets-formula/src/controllers/array-formula-display.controller.ts
+++ b/packages/sheets-formula/src/controllers/array-formula-display.controller.ts
@@ -15,10 +15,11 @@
*/
import type { ICommandInfo } from '@univerjs/core';
-import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import { CellValueType, Disposable, ICommandService, LifecycleStages, OnLifecycle, ThemeService } from '@univerjs/core';
import type { ISetArrayFormulaDataMutationParams } from '@univerjs/engine-formula';
import { FormulaDataModel, SetArrayFormulaDataMutation } from '@univerjs/engine-formula';
import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
+import { getPatternPreview } from '@univerjs/sheets-numfmt';
import { Inject } from '@wendellhu/redi';
@OnLifecycle(LifecycleStages.Ready, ArrayFormulaDisplayController)
@@ -26,7 +27,8 @@ export class ArrayFormulaDisplayController extends Disposable {
constructor(
@ICommandService private readonly _commandService: ICommandService,
@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
- @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel
+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
+ @Inject(ThemeService) private readonly _themeService: ThemeService
) {
super();
@@ -78,6 +80,37 @@ export class ArrayFormulaDisplayController extends Disposable {
return next(cell);
}
+ const numfmtItemMap = this._formulaDataModel.getNumfmtItemMap();
+ const numfmtItem = numfmtItemMap[unitId]?.[subUnitId]?.[row]?.[col];
+
+ if (numfmtItem) {
+ const value = cellData?.v;
+ const type = cellData?.t;
+
+ if (value == null || type !== CellValueType.NUMBER) {
+ return next(cell);
+ }
+
+ const info = getPatternPreview(numfmtItem, value as number);
+
+ if (info.color) {
+ const colorMap = this._themeService.getCurrentTheme();
+ const color = colorMap[`${info.color}500`];
+ return {
+ ...cell,
+ v: info.result,
+ t: CellValueType.STRING,
+ s: { cl: { rgb: color } },
+ };
+ }
+
+ return {
+ ...cell,
+ v: info.result,
+ t: CellValueType.STRING,
+ };
+ }
+
return next({ ...cell, ...cellData });
},
})
diff --git a/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts b/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts
index c05ed52fae..1d212693b5 100644
--- a/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts
@@ -61,6 +61,7 @@ export class FormulaClipboardController extends Disposable {
private _pasteFormulaHook(): ISheetClipboardHook {
const specialPasteFormulaHook: ISheetClipboardHook = {
id: SPECIAL_PASTE_FORMULA,
+ priority: 10,
specialPasteInfo: {
label: 'specialPaste.formula',
},
@@ -96,6 +97,7 @@ export class FormulaClipboardController extends Disposable {
private _pasteWithFormulaHook(): ISheetClipboardHook {
const specialPasteFormulaHook: ISheetClipboardHook = {
id: DEFAULT_PASTE_FORMULA,
+ priority: 10,
onPasteCells: (pasteFrom, pasteTo, data, payload) => {
const copyInfo = {
copyType: payload.copyType || COPY_TYPE.COPY,
diff --git a/packages/sheets-formula/src/controllers/numfmt-formula-display.controller.ts b/packages/sheets-formula/src/controllers/numfmt-formula-display.controller.ts
new file mode 100644
index 0000000000..dcc55f1a02
--- /dev/null
+++ b/packages/sheets-formula/src/controllers/numfmt-formula-display.controller.ts
@@ -0,0 +1,108 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandInfo } from '@univerjs/core';
+import { CellValueType, Disposable, ICommandService, LifecycleStages, OnLifecycle, ThemeService } from '@univerjs/core';
+import type { ISetNumfmtFormulaDataMutationParams } from '@univerjs/engine-formula';
+import { FormulaDataModel, SetNumfmtFormulaDataMutation } from '@univerjs/engine-formula';
+import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
+import { getPatternPreview } from '@univerjs/sheets-numfmt';
+import { Inject } from '@wendellhu/redi';
+
+@OnLifecycle(LifecycleStages.Ready, NumfmtFormulaDisplayController)
+export class NumfmtFormulaDisplayController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
+ @Inject(ThemeService) private readonly _themeService: ThemeService
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ private _initialize(): void {
+ this._commandExecutedListener();
+
+ this._initInterceptorCellContent();
+ }
+
+ private _commandExecutedListener() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ // Synchronous data from worker
+ if (command.id !== SetNumfmtFormulaDataMutation.id) {
+ return;
+ }
+
+ const params = command.params as ISetNumfmtFormulaDataMutationParams;
+
+ if (params == null) {
+ return;
+ }
+
+ const { numfmtItemMap } = params;
+ this._formulaDataModel.updateNumfmtItemMap(numfmtItemMap);
+ })
+ );
+ }
+
+ private _initInterceptorCellContent() {
+ this.disposeWithMe(
+ this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {
+ priority: 98,
+ handler: (cell, location, next) => {
+ const { unitId, subUnitId, row, col } = location;
+
+ const numfmtItemMap = this._formulaDataModel.getNumfmtItemMap();
+ const numfmtItem = numfmtItemMap[unitId]?.[subUnitId]?.[row]?.[col];
+
+ if (numfmtItem == null || numfmtItem === '') {
+ return next(cell);
+ }
+
+ const rawValue = location.worksheet.getCellRaw(row, col);
+ const value = rawValue?.v;
+ const type = rawValue?.t;
+
+ if (value == null || type !== CellValueType.NUMBER) {
+ return next(cell);
+ }
+
+ const info = getPatternPreview(numfmtItem, value as number);
+
+ if (info.color) {
+ const colorMap = this._themeService.getCurrentTheme();
+ const color = colorMap[`${info.color}500`];
+ return {
+ ...cell,
+ v: info.result,
+ t: CellValueType.STRING,
+ s: { cl: { rgb: color } },
+ };
+ }
+
+ return {
+ ...cell,
+ v: info.result,
+ t: CellValueType.STRING,
+ };
+ },
+ })
+ );
+ }
+}
diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
index c52cefae83..d16455ee61 100644
--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
@@ -19,9 +19,11 @@ import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univ
import type {
IDirtyUnitFeatureMap,
IDirtyUnitSheetNameMap,
+ INumfmtItemMap,
ISetFormulaCalculationNotificationMutation,
} from '@univerjs/engine-formula';
import {
+ FormulaDataModel,
FormulaExecutedStateType,
SetFormulaCalculationNotificationMutation,
SetFormulaCalculationStartMutation,
@@ -29,11 +31,13 @@ import {
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import {
ClearSelectionFormatCommand,
+ INumfmtService,
SetBorderCommand,
SetRangeValuesMutation,
SetStyleCommand,
} from '@univerjs/sheets';
+import { Inject } from '@wendellhu/redi';
import { IActiveDirtyManagerService } from '../services/active-dirty-manager.service';
@OnLifecycle(LifecycleStages.Ready, TriggerCalculationController)
@@ -48,7 +52,9 @@ export class TriggerCalculationController extends Disposable {
constructor(
@ICommandService private readonly _commandService: ICommandService,
- @IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService
+ @IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService,
+ @Inject(INumfmtService) private readonly _numfmtService: INumfmtService,
+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel
) {
super();
@@ -126,6 +132,7 @@ export class TriggerCalculationController extends Disposable {
const allDirtyRanges: IUnitRange[] = [];
const allDirtyNameMap: IDirtyUnitSheetNameMap = {};
const allDirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};
+ const numfmtItemMap: INumfmtItemMap = this._formulaDataModel.getNumfmtItemMap();
for (const command of commands) {
const conversion = this._activeDirtyManagerService.get(command.id);
@@ -151,10 +158,44 @@ export class TriggerCalculationController extends Disposable {
}
}
+ // number format data
+ allDirtyRanges.forEach((dirtyRange) => {
+ const { unitId, sheetId } = dirtyRange;
+
+ if (numfmtItemMap[unitId] == null) {
+ numfmtItemMap[unitId] = {};
+ }
+
+ if (numfmtItemMap[unitId]![sheetId] == null) {
+ numfmtItemMap[unitId]![sheetId] = {};
+ }
+
+ const numfmtModel = this._numfmtService.getModel(unitId, sheetId);
+
+ if (!numfmtModel) return;
+
+ const refMode = this._numfmtService.getRefModel(unitId);
+
+ numfmtModel.forValue((row, col, numfmtValue) => {
+ if (numfmtValue && refMode) {
+ const refValue = refMode.getValue(numfmtValue?.i);
+
+ if (!refValue) return;
+
+ if (numfmtItemMap[unitId]![sheetId][row] == null) {
+ numfmtItemMap[unitId]![sheetId][row] = {};
+ }
+
+ numfmtItemMap[unitId]![sheetId][row][col] = refValue.pattern;
+ }
+ });
+ });
+
return {
dirtyRanges: allDirtyRanges,
dirtyNameMap: allDirtyNameMap,
dirtyUnitFeatureMap: allDirtyUnitFeatureMap,
+ numfmtItemMap,
};
}
diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.ts
index 8914eac316..54d1847644 100644
--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts
+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts
@@ -50,6 +50,7 @@ import {
serializeRangeToRefString,
SetArrayFormulaDataMutation,
SetFormulaDataMutation,
+ SetNumfmtFormulaDataMutation,
} from '@univerjs/engine-formula';
import type {
IDeleteRangeMoveLeftCommandParams,
@@ -253,6 +254,7 @@ export class UpdateFormulaController extends Disposable {
this._formulaDataModel.updateFormulaData(unitId, sheetId, cellValue);
this._formulaDataModel.updateArrayFormulaCellData(unitId, sheetId, cellValue);
this._formulaDataModel.updateArrayFormulaRange(unitId, sheetId, cellValue);
+ this._formulaDataModel.updateNumfmtData(unitId, sheetId, cellValue);
this._commandService.executeCommand(
SetFormulaDataMutation.id,
@@ -275,6 +277,16 @@ export class UpdateFormulaController extends Disposable {
remove: true, // remove array formula range shape
}
);
+
+ this._commandService.executeCommand(
+ SetNumfmtFormulaDataMutation.id,
+ {
+ numfmtItemMap: this._formulaDataModel.getNumfmtItemMap(),
+ },
+ {
+ onlyLocal: true,
+ }
+ );
}
private _handleRemoveSheetMutation(params: IRemoveSheetMutationParams) {
@@ -378,6 +390,7 @@ export class UpdateFormulaController extends Disposable {
if (result) {
const { unitSheetNameMap } = this._formulaDataModel.getCalculateData();
let oldFormulaData = this._formulaDataModel.getFormulaData();
+ const oldNumfmtItemMap = this._formulaDataModel.getNumfmtItemMap();
// change formula reference
const { newFormulaData: formulaData, refRanges } = this._getFormulaReferenceMoveInfo(
@@ -436,6 +449,12 @@ export class UpdateFormulaController extends Disposable {
formulaData: this._formulaDataModel.getFormulaData(),
});
+ // offset numfmtItemMap
+ const offsetNumfmtItemMap = offsetFormula(oldNumfmtItemMap, command, unitId, sheetId, selections);
+ this._commandService.executeCommand(SetNumfmtFormulaDataMutation.id, {
+ numfmtItemMap: offsetNumfmtItemMap,
+ });
+
return this._getUpdateFormulaMutations(oldFormulaData, offsetFormulaData);
}
diff --git a/packages/sheets-formula/src/formula-ui-plugin.ts b/packages/sheets-formula/src/formula-ui-plugin.ts
index f1f4b22b0b..38077a78ea 100644
--- a/packages/sheets-formula/src/formula-ui-plugin.ts
+++ b/packages/sheets-formula/src/formula-ui-plugin.ts
@@ -40,6 +40,7 @@ import {
import { FormulaInputService, IFormulaInputService } from './services/formula-input.service';
import { FormulaPromptService, IFormulaPromptService } from './services/prompt.service';
import { IRegisterFunctionService, RegisterFunctionService } from './services/register-function.service';
+import { NumfmtFormulaDisplayController } from './controllers/numfmt-formula-display.controller';
/**
* The configuration of the formula UI plugin.
@@ -86,6 +87,7 @@ export class UniverSheetsFormulaPlugin extends Plugin {
[FormulaAutoFillController],
[FormulaClipboardController],
[ArrayFormulaDisplayController],
+ [NumfmtFormulaDisplayController],
[TriggerCalculationController],
[UpdateFormulaController],
[FormulaEditorShowController],
diff --git a/packages/sheets-formula/src/locale/function-list/date/en-US.ts b/packages/sheets-formula/src/locale/function-list/date/en-US.ts
index f1f539f134..d01386fd09 100644
--- a/packages/sheets-formula/src/locale/function-list/date/en-US.ts
+++ b/packages/sheets-formula/src/locale/function-list/date/en-US.ts
@@ -25,8 +25,9 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ year: { name: 'year', detail: 'The value of the year argument can include one to four digits. Excel interprets the year argument according to the date system your computer is using. By default, Univer uses the 1900 date system, which means the first date is January 1, 1900.' },
+ month: { name: 'month', detail: 'A positive or negative integer representing the month of the year from 1 to 12 (January to December).' },
+ day: { name: 'day', detail: 'A positive or negative integer representing the day of the month from 1 to 31.' },
},
},
DATEDIF: {
@@ -58,7 +59,7 @@ export default {
},
},
DAY: {
- description: 'Converts a serial number to a day of the month',
+ description: 'Returns the day of a date, represented by a serial number. The day is given as an integer ranging from 1 to 31.',
abstract: 'Converts a serial number to a day of the month',
links: [
{
@@ -67,8 +68,7 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ serialNumber: { name: 'Serial Number', detail: 'The date of the day you are trying to find. Dates should be entered by using the DATE function, or as results of other formulas or functions. For example, use DATE(2008,5,23) for the 23rd day of May, 2008.' },
},
},
DAYS: {
@@ -100,7 +100,7 @@ export default {
},
},
EDATE: {
- description: 'Returns the serial number of the date that is the indicated number of months before or after the start date',
+ description: 'Returns 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.',
abstract: 'Returns the serial number of the date that is the indicated number of months before or after the start date',
links: [
{
@@ -109,8 +109,8 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ startDate: { name: 'Start Date', detail: 'A date that represents the start date. Dates should be entered by using the DATE function, or as results of other formulas or functions. For example, use DATE(2008,5,23) for the 23rd day of May, 2008. Problems can occur if dates are entered as text.' },
+ months: { name: 'Months', detail: 'The number of months before or after start_date. A positive value for months yields a future date; a negative value yields a past date.' },
},
},
EOMONTH: {
@@ -170,7 +170,7 @@ export default {
},
},
MONTH: {
- description: 'Converts a serial number to a month',
+ description: 'Returns the month of a date represented by a serial number. The month is given as an integer, ranging from 1 (January) to 12 (December).',
abstract: 'Converts a serial number to a month',
links: [
{
@@ -179,8 +179,7 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ serialNumber: { name: 'Serial Number', detail: 'Required. The date of the month you are trying to find. Dates should be entered by using the DATE function, or as results of other formulas or functions. For example, use DATE(2008,5,23) for the 23rd day of May, 2008.' },
},
},
NETWORKDAYS: {
@@ -277,8 +276,6 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
},
},
WEEKDAY: {
@@ -338,7 +335,7 @@ export default {
},
},
YEAR: {
- description: 'Converts a serial number to a year',
+ description: 'Returns the year corresponding to a date. The year is returned as an integer in the range 1900-9999.',
abstract: 'Converts a serial number to a year',
links: [
{
@@ -347,8 +344,7 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ serialNumber: { name: 'Serial Number', detail: 'The date of the year you want to find. Dates should be entered by using the DATE function, or as results of other formulas or functions. For example, use DATE(2008,5,23) for the 23rd day of May, 2008. Problems can occur if dates are entered as text.' },
},
},
YEARFRAC: {
diff --git a/packages/sheets-formula/src/locale/function-list/date/ja-JP.ts b/packages/sheets-formula/src/locale/function-list/date/ja-JP.ts
index f5beed5b64..814becd8da 100644
--- a/packages/sheets-formula/src/locale/function-list/date/ja-JP.ts
+++ b/packages/sheets-formula/src/locale/function-list/date/ja-JP.ts
@@ -25,8 +25,9 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ year: { name: '年', detail: 'year 引数の値 には 、1 ~ 4 桁の数字を指定できます。 Excel は、コンピューター が使用 している日付システムに応じて年の引数を解釈します。 既定では、Univer では 1900 年の日付システムが使用されます。つまり、最初の日付は 1900 年 1 月 1 日です。' },
+ month: { name: '月', detail: '1 ~ 12 (1 月から 12 月) の月を表す正または負の整数です。' },
+ day: { name: '日', detail: '1 ~ 31 の月の日を表す正または負の整数です。' },
},
},
DATEDIF: {
@@ -58,7 +59,7 @@ export default {
},
},
DAY: {
- description: 'シリアル値を日付に変換します。',
+ description: 'シリアル番号で表された、日付の日情報を返します。日情報は 1 ~ 31 の範囲内の整数で示されます。',
abstract: 'シリアル値を日付に変換します。',
links: [
{
@@ -67,8 +68,7 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ serialNumber: { name: 'シリアル値', detail: '検索する日付を指定します。 日付は、DATE 関数を使って入力するか、他の数式または他の関数の結果を指定します。 たとえば、2008 年 5 月 23 日を入力する場合は、DATE(2008,5,23) を使用します。' },
},
},
DAYS: {
@@ -100,7 +100,7 @@ export default {
},
},
EDATE: {
- description: '開始日から起算して、指定した月数だけ前または後の日付に対応するシリアル値を返します。',
+ description: '開始日から起算して、指定された月数だけ前または後の日付に対応するシリアル値を返します。 この関数を使用すると、伝票の発行日と同じ日に当たる支払日や満期日の日付を計算することができます。',
abstract: '開始日から起算して、指定した月数だけ前または後の日付に対応するシリアル値を返します。',
links: [
{
@@ -109,8 +109,8 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ startDate: { name: '開始日', detail: '起算日を表す日付を指定します。 日付は、DATE 関数を使って入力するか、他の数式または他の関数の結果を指定します。 たとえば、2008 年 5 月 23 日を入力する場合は、DATE(2008,5,23) を使用します。 日付を文字列として入力した場合、エラーが発生することがあります。' },
+ months: { name: '月', detail: '開始日から起算した月数を指定します。 "月" に正の数を指定すると起算日より後の日付を返し、負の数を指定すると起算日より前の日付を返します。' },
},
},
EOMONTH: {
@@ -179,8 +179,7 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ serialNumber: { name: 'シリアル値', detail: '検索する月の日付を指定します。 日付は、DATE 関数を使って入力するか、他の数式または他の関数の結果として指定します。 たとえば、2008 年 5 月 23 日を入力する場合は、DATE(2008,5,23) を使用します。' },
},
},
NETWORKDAYS: {
@@ -277,8 +276,6 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
},
},
WEEKDAY: {
@@ -338,7 +335,7 @@ export default {
},
},
YEAR: {
- description: 'シリアル値を年に変換します。',
+ description: '日付に対応する年を返します。 戻り値は、1900 (年) ~ 9999 (年) の範囲の整数となります。',
abstract: 'シリアル値を年に変換します。',
links: [
{
@@ -347,8 +344,7 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ serialNumber: { name: 'シリアル値', detail: '検索する年の日付を指定します。 日付は、DATE 関数を使って入力するか、他の数式または他の関数の結果として指定します。 たとえば、2008 年 5 月 23 日を入力する場合は、DATE(2008,5,23) を使用します。 日付を文字列として入力した場合、エラーが発生することがあります。' },
},
},
YEARFRAC: {
diff --git a/packages/sheets-formula/src/locale/function-list/date/zh-CN.ts b/packages/sheets-formula/src/locale/function-list/date/zh-CN.ts
index b0daba469a..ae496e2c7b 100644
--- a/packages/sheets-formula/src/locale/function-list/date/zh-CN.ts
+++ b/packages/sheets-formula/src/locale/function-list/date/zh-CN.ts
@@ -16,7 +16,7 @@
export default {
DATE: {
- description: '返回特定日期的序列号',
+ description: '采用三个单独的值并将它们合并为一个日期。',
abstract: '返回特定日期的序列号',
links: [
{
@@ -25,8 +25,9 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ year: { name: '年', detail: '可以包含 1 到 4 位数字。 Excel 根据计算机使用的日期系统解释 year 参数。 默认情况下,Univer 使用 1900 日期系统,这意味着第一个日期是 1900 年 1 月 1 日。' },
+ month: { name: '月', detail: '一个正整数或负整数,表示一年中从 1 月至 12 月(一月到十二月)的各个月。' },
+ day: { name: '日', detail: '一个正整数或负整数,表示一月中从 1 日到 31 日的各天。' },
},
},
DATEDIF: {
@@ -58,7 +59,7 @@ export default {
},
},
DAY: {
- description: '将序列号转换为月份日期',
+ description: '返回以序列数表示的某日期的天数。天数是介于 1 到 31 之间的整数。',
abstract: '将序列号转换为月份日期',
links: [
{
@@ -67,8 +68,7 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ serialNumber: { name: '日期序列号', detail: '要查找的日期。 应使用 DATE 函数输入日期,或者将日期作为其他公式或函数的结果输入。 例如,使用函数 DATE(2008,5,23) 输入 2008 年 5 月 23 日。' },
},
},
DAYS: {
@@ -100,7 +100,7 @@ export default {
},
},
EDATE: {
- description: '返回用于表示开始日期之前或之后月数的日期的序列号',
+ description: '返回表示某个日期的序列号,该日期与指定日期 (start_date) 相隔(之前或之后)指示的月份数。 使用函数 EDATE 可以计算与发行日处于一月中同一天的到期日的日期。',
abstract: '返回用于表示开始日期之前或之后月数的日期的序列号',
links: [
{
@@ -109,8 +109,8 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ startDate: { name: '开始日期', detail: '一个代表开始日期的日期。 应使用 DATE 函数输入日期,或者将日期作为其他公式或函数的结果输入。 例如,使用函数 DATE(2008,5,23) 输入 2008 年 5 月 23 日。' },
+ months: { name: '月份', detail: 'Start Date 之前或之后的月份数。 Months 为正值将生成未来日期;为负值将生成过去日期。' },
},
},
EOMONTH: {
@@ -170,7 +170,7 @@ export default {
},
},
MONTH: {
- description: '将序列号转换为月',
+ description: '返回日期(以序列数表示)中的月份。 月份是介于 1(一月)到 12(十二月)之间的整数。',
abstract: '将序列号转换为月',
links: [
{
@@ -179,8 +179,7 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ serialNumber: { name: '日期序列号', detail: '要查找的月份的日期。 应使用 DATE 函数输入日期,或者将日期作为其他公式或函数的结果输入。 例如,使用函数 DATE(2008,5,23) 输入 2008 年 5 月 23 日。' },
},
},
NETWORKDAYS: {
@@ -277,8 +276,6 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
},
},
WEEKDAY: {
@@ -338,7 +335,7 @@ export default {
},
},
YEAR: {
- description: '将序列号转换为年',
+ description: '返回对应于某个日期的年份。 Year 作为 1900 - 9999 之间的整数返回。',
abstract: '将序列号转换为年',
links: [
{
@@ -347,8 +344,7 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ serialNumber: { name: '日期序列号', detail: '要查找的年份的日期。 应使用 DATE 函数输入日期,或者将日期作为其他公式或函数的结果输入。 例如,使用函数 DATE(2008,5,23) 输入 2008 年 5 月 23 日。 如果日期以文本形式输入,则会出现问题。' },
},
},
YEARFRAC: {
diff --git a/packages/sheets-formula/src/locale/function-list/lookup/en-US.ts b/packages/sheets-formula/src/locale/function-list/lookup/en-US.ts
index 5a245cb16a..5cab391d4f 100644
--- a/packages/sheets-formula/src/locale/function-list/lookup/en-US.ts
+++ b/packages/sheets-formula/src/locale/function-list/lookup/en-US.ts
@@ -326,7 +326,7 @@ export default {
},
},
MATCH: {
- description: 'Looks up values in a reference or array',
+ description: 'The MATCH function searches for a specified item in a range of cells, and then returns the relative position of that item in the range. For example, if the range A1:A3 contains the values 5, 25, and 38, then the formula =MATCH(25,A1:A3,0) returns the number 2, because 25 is the second item in the range.',
abstract: 'Looks up values in a reference or array',
links: [
{
@@ -335,8 +335,9 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ lookupValue: { name: 'lookup_value', detail: 'The value that you want to match in lookup_array. For example, when you look up someone\'s number in a telephone book, you are using the person\'s name as the lookup value, but the telephone number is the value you want. The lookup_value argument can be a value (number, text, or logical value) or a cell reference to a number, text, or logical value.' },
+ lookupArray: { name: 'lookup_array', detail: 'The range of cells being searched.' },
+ matchType: { name: 'match_type', detail: 'The number -1, 0, or 1. The match_type argument specifies how Excel matches lookup_value with values in lookup_array. The default value for this argument is 1.' },
},
},
OFFSET: {
@@ -597,8 +598,8 @@ export default {
},
},
XMATCH: {
- description: 'Returns the&nbsp;relative&nbsp;position of an item in an array or range of cells.&nbsp;',
- abstract: 'Returns the&nbsp;relative&nbsp;position of an item in an array or range of cells.&nbsp;',
+ description: 'Searches for a specified item in an array or range of cells, and then returns the item\'s relative position.',
+ abstract: 'Returns the&nbsp;relative&nbsp;position of an item in an array or range of cells.',
links: [
{
title: 'Instruction',
@@ -606,8 +607,10 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ lookupValue: { name: 'lookup_value', detail: 'The lookup value' },
+ lookupArray: { name: 'lookup_array', detail: 'The array or range to search' },
+ matchMode: { name: 'match_mode', detail: 'Specify the match type:\n0 - Exact match (default)\n-1 - Exact match or next smallest item\n1 - Exact match or next largest item\n2 - A wildcard match where *, ?, and ~ have special meaning.' },
+ searchMode: { name: 'search_mode', detail: 'Specify the search type:\n1 - Search first-to-last (default)\n-1 - Search last-to-first (reverse search).\n2 - Perform a binary search that relies on lookup_array being sorted in ascending order. If not sorted, invalid results will be returned.\n-2 - Perform a binary search that relies on lookup_array being sorted in descending order. If not sorted, invalid results will be returned.' },
},
},
};
diff --git a/packages/sheets-formula/src/locale/function-list/lookup/ja-JP.ts b/packages/sheets-formula/src/locale/function-list/lookup/ja-JP.ts
index a2d967969e..3048a53439 100644
--- a/packages/sheets-formula/src/locale/function-list/lookup/ja-JP.ts
+++ b/packages/sheets-formula/src/locale/function-list/lookup/ja-JP.ts
@@ -315,7 +315,7 @@ export default {
},
},
MATCH: {
- description: '照合の型に従って参照または配列に含まれる値を検索し、検査値と一致する要素の相対的な位置を数値で返します。',
+ description: 'MATCH 関数は、範囲 のセルの範囲で指定した項目を検索し、その範囲内の項目の相対的な位置を返します。 たとえば、範囲 A1:A3 に値 5、25、38 が含まれている場合、数式「=MATCH(25,A1:A3,0)」を入力すると、範囲内では 25 が 2 番目の項目であるため、数字 2 が返されます。',
abstract: '照合の型に従って参照または配列に含まれる値を検索し、検査値と一致する要素の相対的な位置を数値で返します。',
links: [
{
@@ -324,8 +324,9 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ lookupValue: { name: '検査値', detail: '検査範囲の中で照合する値を指定します。 たとえば、電話番号帳を使ってある人の電話番号を調べるとき、検査値としてその人の氏名を指定しますが、実際に検索するのは電話番号です。検査値には、値 (数値、文字列、または論理値)、またはこれらの値に対するセル参照を指定できます。' },
+ lookupArray: { name: '検査範囲', detail: '検索するセルの範囲を指定します。' },
+ matchType: { name: '照合の型', detail: '-1、0、1 の数値のいずれかを指定します。 照合の型には、検査範囲の中で検査値を探す方法を指定します。 この引数の既定値は 1 です。' },
},
},
OFFSET: {
@@ -586,8 +587,8 @@ export default {
},
},
XMATCH: {
- description: 'セルの配列またはセルの範囲内で指定された項目の相対的な位置を返します。&nbsp;',
- abstract: 'セルの配列またはセルの範囲内で指定された項目の相対的な位置を返します。&nbsp;',
+ description: '指定された項目を配列内またはセル範囲内で検索し、項目の相対位置を返します。 ',
+ abstract: 'セルの配列またはセルの範囲内で指定された項目の相対的な位置を返します。',
links: [
{
title: '指導',
@@ -595,8 +596,10 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ lookupValue: { name: '検索値', detail: '参照値' },
+ lookupArray: { name: '検索範囲', detail: '検索する配列または範囲' },
+ matchMode: { name: '一致モード', detail: '一致の種類を指定します:\n0 - 完全一致 (既定)\n-1 - 完全一致または最も近い小さな値の項目\n1 - 完全一致または最も近い大きな値の項目\n2 - *、?、および 〜 が特別な意味を持つワイルドカードの一致。' },
+ searchMode: { name: '検索モード', detail: '検索モードを指定します。\n1 - 先頭から末尾へ検索 (既定)\n-1 - 末尾から先頭へ検索 (逆方向検索)。\n2 - 検索範囲が昇順に並んでいることを前提にしてバイナリ検索を実行する。 並べ替えられていない場合、無効な結果が返されます。\n-2 - 降順で並べ替えられた検索範囲を使用してバイナリ検索を実行します。 並べ替えられていない場合、無効な結果が返されます。' },
},
},
};
diff --git a/packages/sheets-formula/src/locale/function-list/lookup/zh-CN.ts b/packages/sheets-formula/src/locale/function-list/lookup/zh-CN.ts
index 47d2c63d39..94221751b9 100644
--- a/packages/sheets-formula/src/locale/function-list/lookup/zh-CN.ts
+++ b/packages/sheets-formula/src/locale/function-list/lookup/zh-CN.ts
@@ -313,7 +313,7 @@ export default {
},
},
MATCH: {
- description: '在引用或数组中查找值',
+ description: '使用 MATCH 函数在 范围 单元格中搜索特定的项,然后返回该项在此区域中的相对位置。 例如,如果 A1:A3 区域中包含值 5、25 和 38,那么公式 =MATCH(25,A1:A3,0) 返回数字 2,因为 25 是该区域中的第二项。',
abstract: '在引用或数组中查找值',
links: [
{
@@ -322,8 +322,9 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ lookupValue: { name: '查找值', detail: '要在 lookup_array 中匹配的值。 例如,如果要在电话簿中查找某人的电话号码,则应该将姓名作为查找值,但实际上需要的是电话号码。lookup_value 参数可以为值(数字、文本或逻辑值)或对数字、文本或逻辑值的单元格引用。' },
+ lookupArray: { name: '搜索区域', detail: '要搜索的单元格区域。' },
+ matchType: { name: '匹配类型', detail: '数字 -1、0 或 1。 match_type 参数指定 Excel 如何将 lookup_value 与 lookup_array 中的值匹配。 此参数的默认值为 1。' },
},
},
OFFSET: {
@@ -586,8 +587,8 @@ export default {
},
},
XMATCH: {
- description: '返回项目在数组或单元格区域中的相对位置。&nbsp;',
- abstract: '返回项目在数组或单元格区域中的相对位置。&nbsp;',
+ description: '在数组或单元格区域中搜索指定项,然后返回项的相对位置。',
+ abstract: '返回项目在数组或单元格区域中的相对位置。',
links: [
{
title: '教学',
@@ -595,8 +596,10 @@ export default {
},
],
functionParameter: {
- number1: { name: 'number1', detail: 'first' },
- number2: { name: 'number2', detail: 'second' },
+ lookupValue: { name: '查找值', detail: '查找值' },
+ lookupArray: { name: '搜索区域', detail: '要搜索的数组或区域' },
+ matchMode: { name: '匹配类型', detail: '指定匹配类型:\n0 - 完全匹配(默认值)\n-1 - 完全匹配或下一个最小项\n1 - 完全匹配或下一个最大项\n2 - 通配符匹配,其中 *, ? 和 ~ 有特殊含义。' },
+ searchMode: { name: '搜索类型', detail: '指定搜索类型:\n1 - 搜索从第一到最后一个(默认值)\n-1 - 搜索从最后到第一个(反向搜索)。\n2 - 执行依赖于 lookup_array 按升序排序的二进制搜索。 如果未排序,将返回无效结果。\n2 - 执行依赖于 lookup_array 按降序排序的二进制搜索。 如果未排序,将返回无效结果。' },
},
},
};
diff --git a/packages/sheets-formula/src/services/function-list/date.ts b/packages/sheets-formula/src/services/function-list/date.ts
index c672f15d36..879df0befa 100644
--- a/packages/sheets-formula/src/services/function-list/date.ts
+++ b/packages/sheets-formula/src/services/function-list/date.ts
@@ -24,16 +24,23 @@ export const FUNCTION_LIST_DATE: IFunctionInfo[] = [
abstract: 'formula.functionList.DATE.abstract',
functionParameter: [
{
- name: 'formula.functionList.DATE.functionParameter.number1.name',
- detail: 'formula.functionList.DATE.functionParameter.number1.detail',
- example: 'A1:A20',
+ name: 'formula.functionList.DATE.functionParameter.year.name',
+ detail: 'formula.functionList.DATE.functionParameter.year.detail',
+ example: '2024',
require: 1,
repeat: 0,
},
{
- name: 'formula.functionList.DATE.functionParameter.number2.name',
- detail: 'formula.functionList.DATE.functionParameter.number2.detail',
- example: 'A1:A20',
+ name: 'formula.functionList.DATE.functionParameter.month.name',
+ detail: 'formula.functionList.DATE.functionParameter.month.detail',
+ example: '1',
+ require: 1,
+ repeat: 0,
+ },
+ {
+ name: 'formula.functionList.DATE.functionParameter.day.name',
+ detail: 'formula.functionList.DATE.functionParameter.day.detail',
+ example: '1',
require: 1,
repeat: 0,
},
@@ -90,15 +97,8 @@ export const FUNCTION_LIST_DATE: IFunctionInfo[] = [
abstract: 'formula.functionList.DAY.abstract',
functionParameter: [
{
- name: 'formula.functionList.DAY.functionParameter.number1.name',
- detail: 'formula.functionList.DAY.functionParameter.number1.detail',
- example: 'A1:A20',
- require: 1,
- repeat: 0,
- },
- {
- name: 'formula.functionList.DAY.functionParameter.number2.name',
- detail: 'formula.functionList.DAY.functionParameter.number2.detail',
+ name: 'formula.functionList.DAY.functionParameter.serialNumber.name',
+ detail: 'formula.functionList.DAY.functionParameter.serialNumber.detail',
example: 'A1:A20',
require: 1,
repeat: 0,
@@ -156,16 +156,16 @@ export const FUNCTION_LIST_DATE: IFunctionInfo[] = [
abstract: 'formula.functionList.EDATE.abstract',
functionParameter: [
{
- name: 'formula.functionList.EDATE.functionParameter.number1.name',
- detail: 'formula.functionList.EDATE.functionParameter.number1.detail',
- example: 'A1:A20',
+ name: 'formula.functionList.EDATE.functionParameter.startDate.name',
+ detail: 'formula.functionList.EDATE.functionParameter.startDate.detail',
+ example: 'A1',
require: 1,
repeat: 0,
},
{
- name: 'formula.functionList.EDATE.functionParameter.number2.name',
- detail: 'formula.functionList.EDATE.functionParameter.number2.detail',
- example: 'A1:A20',
+ name: 'formula.functionList.EDATE.functionParameter.months.name',
+ detail: 'formula.functionList.EDATE.functionParameter.months.detail',
+ example: '1',
require: 1,
repeat: 0,
},
@@ -266,15 +266,8 @@ export const FUNCTION_LIST_DATE: IFunctionInfo[] = [
abstract: 'formula.functionList.MONTH.abstract',
functionParameter: [
{
- name: 'formula.functionList.MONTH.functionParameter.number1.name',
- detail: 'formula.functionList.MONTH.functionParameter.number1.detail',
- example: 'A1:A20',
- require: 1,
- repeat: 0,
- },
- {
- name: 'formula.functionList.MONTH.functionParameter.number2.name',
- detail: 'formula.functionList.MONTH.functionParameter.number2.detail',
+ name: 'formula.functionList.MONTH.functionParameter.serialNumber.name',
+ detail: 'formula.functionList.MONTH.functionParameter.serialNumber.detail',
example: 'A1:A20',
require: 1,
repeat: 0,
@@ -419,20 +412,6 @@ export const FUNCTION_LIST_DATE: IFunctionInfo[] = [
description: 'formula.functionList.TODAY.description',
abstract: 'formula.functionList.TODAY.abstract',
functionParameter: [
- {
- name: 'formula.functionList.TODAY.functionParameter.number1.name',
- detail: 'formula.functionList.TODAY.functionParameter.number1.detail',
- example: 'A1:A20',
- require: 1,
- repeat: 0,
- },
- {
- name: 'formula.functionList.TODAY.functionParameter.number2.name',
- detail: 'formula.functionList.TODAY.functionParameter.number2.detail',
- example: 'A1:A20',
- require: 1,
- repeat: 0,
- },
],
},
{
@@ -530,15 +509,8 @@ export const FUNCTION_LIST_DATE: IFunctionInfo[] = [
abstract: 'formula.functionList.YEAR.abstract',
functionParameter: [
{
- name: 'formula.functionList.YEAR.functionParameter.number1.name',
- detail: 'formula.functionList.YEAR.functionParameter.number1.detail',
- example: 'A1:A20',
- require: 1,
- repeat: 0,
- },
- {
- name: 'formula.functionList.YEAR.functionParameter.number2.name',
- detail: 'formula.functionList.YEAR.functionParameter.number2.detail',
+ name: 'formula.functionList.YEAR.functionParameter.serialNumber.name',
+ detail: 'formula.functionList.YEAR.functionParameter.serialNumber.detail',
example: 'A1:A20',
require: 1,
repeat: 0,
diff --git a/packages/sheets-formula/src/services/function-list/lookup.ts b/packages/sheets-formula/src/services/function-list/lookup.ts
index 536e8c0492..889bcce365 100644
--- a/packages/sheets-formula/src/services/function-list/lookup.ts
+++ b/packages/sheets-formula/src/services/function-list/lookup.ts
@@ -484,19 +484,26 @@ export const FUNCTION_LIST_LOOKUP: IFunctionInfo[] = [
abstract: 'formula.functionList.MATCH.abstract',
functionParameter: [
{
- name: 'formula.functionList.MATCH.functionParameter.number1.name',
- detail: 'formula.functionList.MATCH.functionParameter.number1.detail',
- example: 'A1:A20',
+ name: 'formula.functionList.MATCH.functionParameter.lookupValue.name',
+ detail: 'formula.functionList.MATCH.functionParameter.lookupValue.detail',
+ example: '10',
require: 1,
repeat: 0,
},
{
- name: 'formula.functionList.MATCH.functionParameter.number2.name',
- detail: 'formula.functionList.MATCH.functionParameter.number2.detail',
+ name: 'formula.functionList.MATCH.functionParameter.lookupArray.name',
+ detail: 'formula.functionList.MATCH.functionParameter.lookupArray.detail',
example: 'A1:A20',
require: 1,
repeat: 0,
},
+ {
+ name: 'formula.functionList.MATCH.functionParameter.matchType.name',
+ detail: 'formula.functionList.MATCH.functionParameter.matchType.detail',
+ example: '1',
+ require: 0,
+ repeat: 0,
+ },
],
},
{
@@ -921,19 +928,33 @@ export const FUNCTION_LIST_LOOKUP: IFunctionInfo[] = [
abstract: 'formula.functionList.XMATCH.abstract',
functionParameter: [
{
- name: 'formula.functionList.XMATCH.functionParameter.number1.name',
- detail: 'formula.functionList.XMATCH.functionParameter.number1.detail',
- example: 'A1:A20',
+ name: 'formula.functionList.XMATCH.functionParameter.lookupValue.name',
+ detail: 'formula.functionList.XMATCH.functionParameter.lookupValue.detail',
+ example: 'B1',
require: 1,
repeat: 0,
},
{
- name: 'formula.functionList.XMATCH.functionParameter.number2.name',
- detail: 'formula.functionList.XMATCH.functionParameter.number2.detail',
+ name: 'formula.functionList.XMATCH.functionParameter.lookupArray.name',
+ detail: 'formula.functionList.XMATCH.functionParameter.lookupArray.detail',
example: 'A1:A20',
require: 1,
repeat: 0,
},
+ {
+ name: 'formula.functionList.XMATCH.functionParameter.matchMode.name',
+ detail: 'formula.functionList.XMATCH.functionParameter.matchMode.detail',
+ example: '0',
+ require: 0,
+ repeat: 0,
+ },
+ {
+ name: 'formula.functionList.XMATCH.functionParameter.searchMode.name',
+ detail: 'formula.functionList.XMATCH.functionParameter.searchMode.detail',
+ example: '1',
+ require: 0,
+ repeat: 0,
+ },
],
},
];
diff --git a/packages/sheets-formula/src/views/prompt/help-function/index.module.less b/packages/sheets-formula/src/views/prompt/help-function/index.module.less
index 4a1f657f8b..89cae77703 100644
--- a/packages/sheets-formula/src/views/prompt/help-function/index.module.less
+++ b/packages/sheets-formula/src/views/prompt/help-function/index.module.less
@@ -88,6 +88,7 @@
&-detail {
font-size: var(--font-size-xxs);
font-weight: 400;
+ white-space: pre-wrap;
color: rgb(var(--text-color-secondary));
}
}
diff --git a/packages/sheets-formula/vite.config.ts b/packages/sheets-formula/vite.config.ts
index c4dc71e03d..ab5537ac45 100644
--- a/packages/sheets-formula/vite.config.ts
+++ b/packages/sheets-formula/vite.config.ts
@@ -28,6 +28,7 @@ export default ({ mode }) => createViteConfig({
'@univerjs/engine-render': 'UniverEngineRender',
'@univerjs/sheets': 'UniverSheets',
'@univerjs/sheets-ui': 'UniverSheetsUi',
+ '@univerjs/sheets-numfmt': 'UniverSheetsNumfmt',
'@univerjs/ui': 'UniverUi',
'@wendellhu/redi': '@wendellhu/redi',
'@wendellhu/redi/react-bindings': '@wendellhu/redi/react-bindings',
diff --git a/packages/sheets-numfmt/package.json b/packages/sheets-numfmt/package.json
index 347aab1ac6..1ad6332f57 100644
--- a/packages/sheets-numfmt/package.json
+++ b/packages/sheets-numfmt/package.json
@@ -54,6 +54,7 @@
"peerDependencies": {
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
+ "@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-numfmt": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/sheets": "workspace:*",
@@ -70,6 +71,7 @@
"@types/react": "^18.2.56",
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
+ "@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-numfmt": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/shared": "workspace:*",
diff --git a/packages/sheets-numfmt/src/index.ts b/packages/sheets-numfmt/src/index.ts
index e252b9ead6..901bfa7a36 100644
--- a/packages/sheets-numfmt/src/index.ts
+++ b/packages/sheets-numfmt/src/index.ts
@@ -17,3 +17,4 @@
export { type ISetNumfmtCommandParams, SetNumfmtCommand } from './commands/commands/set-numfmt.command';
export { enUS, zhCN } from './locale';
export { UniverSheetsNumfmtPlugin } from './numfmt-plugin';
+export { getPatternPreview } from './utils/pattern';
diff --git a/packages/sheets-numfmt/src/menu/menu.ts b/packages/sheets-numfmt/src/menu/menu.ts
index 948f2ea5a2..c780b344d3 100644
--- a/packages/sheets-numfmt/src/menu/menu.ts
+++ b/packages/sheets-numfmt/src/menu/menu.ts
@@ -28,6 +28,7 @@ import { getMenuHiddenObservable, MenuGroup, MenuItemType, MenuPosition } from '
import type { IAccessor } from '@wendellhu/redi';
import { merge, Observable } from 'rxjs';
+import { FormulaDataModel } from '@univerjs/engine-formula';
import { MENU_OPTIONS } from '../base/const/MENU-OPTIONS';
import { AddDecimalCommand } from '../commands/commands/add-decimal.command';
import { SetCurrencyCommand } from '../commands/commands/set-currency.command';
@@ -96,6 +97,7 @@ export const FactoryOtherMenuItem = (componentManager: ComponentManager) => {
return (_accessor: IAccessor) => {
const numfmtService = _accessor.get(INumfmtService);
+ const formulaDataModel = _accessor.get(FormulaDataModel);
const univerInstanceService = _accessor.get(IUniverInstanceService);
const commandService = _accessor.get(ICommandService);
const localeService = _accessor.get(LocaleService);
@@ -121,11 +123,14 @@ export const FactoryOtherMenuItem = (componentManager: ComponentManager) => {
const range = selections[0].range;
const row = range.startRow;
const col = range.startColumn;
+
const numfmtValue = numfmtService.getValue(workbook.getUnitId(), worksheet.getSheetId(), row, col);
+ const numfmtValueByFormula = formulaDataModel.getNumfmtValue(workbook.getUnitId(), worksheet.getSheetId(), row, col);
+
+ const pattern = numfmtValue?.pattern || numfmtValueByFormula;
let value: string = localeService.t('sheet.numfmt.general');
- if (numfmtValue) {
- const pattern = numfmtValue.pattern;
+ if (pattern) {
const item = MENU_OPTIONS.filter((item) => typeof item === 'object' && item.pattern).find(
(item) => isPatternEqualWithoutDecimal(pattern, (item as { pattern: string }).pattern)
);
diff --git a/packages/sheets-numfmt/vite.config.ts b/packages/sheets-numfmt/vite.config.ts
index 8e4292cd0a..44482821f8 100644
--- a/packages/sheets-numfmt/vite.config.ts
+++ b/packages/sheets-numfmt/vite.config.ts
@@ -8,6 +8,7 @@ export default ({ mode }) => createViteConfig({
'@univerjs/core',
'@univerjs/design',
'@univerjs/engine-formula',
+ '@univerjs/engine-numfmt',
'@univerjs/engine-render',
'@univerjs/sheets',
'@univerjs/sheets-ui',
@@ -24,6 +25,7 @@ export default ({ mode }) => createViteConfig({
'@univerjs/core': 'UniverCore',
'@univerjs/design': 'UniverDesign',
'@univerjs/engine-formula': 'UniverEngineFormula',
+ '@univerjs/engine-numfmt': 'UniverEngineNumfmt',
'@univerjs/engine-render': 'UniverEngineRender',
'@univerjs/sheets': 'UniverSheets',
'@univerjs/sheets-ui': 'UniverSheetsUi',
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 23dd86d2f1..2e62dc77e4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -763,6 +763,9 @@ importers:
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets
+ '@univerjs/sheets-numfmt':
+ specifier: workspace:*
+ version: link:../sheets-numfmt
'@univerjs/sheets-ui':
specifier: workspace:*
version: link:../sheets-ui
@@ -809,6 +812,9 @@ importers:
'@univerjs/design':
specifier: workspace:*
version: link:../design
+ '@univerjs/engine-formula':
+ specifier: workspace:*
+ version: link:../engine-formula
'@univerjs/engine-numfmt':
specifier: workspace:*
version: link:../engine-numfmt
@@ -1205,7 +1211,7 @@ packages:
'@eslint-types/typescript-eslint': 6.19.1
'@eslint-types/unicorn': 50.0.1
'@stylistic/eslint-plugin': 1.5.4([email protected])([email protected])
- '@typescript-eslint/eslint-plugin': 6.20.0(@typescript-eslint/[email protected])([email protected])([email protected])
+ '@typescript-eslint/eslint-plugin': 6.21.0(@typescript-eslint/[email protected])([email protected])([email protected])
'@typescript-eslint/parser': 6.20.0([email protected])([email protected])
eslint: 8.56.0
eslint-config-flat-gitignore: 0.1.2
@@ -1214,7 +1220,7 @@ packages:
eslint-plugin-eslint-comments: 3.2.0([email protected])
eslint-plugin-format: 0.1.0([email protected])
eslint-plugin-i: 2.29.1(@typescript-eslint/[email protected])([email protected])
- eslint-plugin-jsdoc: 48.0.4([email protected])
+ eslint-plugin-jsdoc: 48.0.5([email protected])
eslint-plugin-jsonc: 2.13.0([email protected])
eslint-plugin-markdown: 3.0.1([email protected])
eslint-plugin-n: 16.6.2([email protected])
@@ -1225,8 +1231,8 @@ packages:
eslint-plugin-react-refresh: 0.4.5([email protected])
eslint-plugin-toml: 0.9.2([email protected])
eslint-plugin-unicorn: 50.0.1([email protected])
- eslint-plugin-unused-imports: 3.0.0(@typescript-eslint/[email protected])([email protected])
- eslint-plugin-vitest: 0.3.21(@typescript-eslint/[email protected])([email protected])([email protected])
+ eslint-plugin-unused-imports: 3.0.0(@typescript-eslint/[email protected])([email protected])
+ eslint-plugin-vitest: 0.3.21(@typescript-eslint/[email protected])([email protected])([email protected])
eslint-plugin-vue: 9.21.1([email protected])
eslint-plugin-yml: 1.12.2([email protected])
eslint-processor-vue-blocks: 0.1.1(@vue/[email protected])([email protected])
@@ -5327,7 +5333,7 @@ packages:
peerDependencies:
eslint: '*'
dependencies:
- '@typescript-eslint/utils': 6.19.0([email protected])([email protected])
+ '@typescript-eslint/utils': 6.21.0([email protected])([email protected])
eslint: 8.56.0
transitivePeerDependencies:
- supports-color
@@ -5341,7 +5347,7 @@ packages:
eslint: '>=8.40.0'
dependencies:
'@stylistic/eslint-plugin-js': 1.5.4([email protected])
- '@typescript-eslint/utils': 6.19.0([email protected])([email protected])
+ '@typescript-eslint/utils': 6.21.0([email protected])([email protected])
eslint: 8.56.0
transitivePeerDependencies:
- supports-color
@@ -5727,8 +5733,8 @@ packages:
'@types/yargs-parser': 21.0.3
dev: true
- /@typescript-eslint/[email protected](@typescript-eslint/[email protected])([email protected])([email protected]):
- resolution: {integrity: sha512-fTwGQUnjhoYHeSF6m5pWNkzmDDdsKELYrOBxhjMrofPqCkoC2k3B2wvGHFxa1CTIqkEn88nlW1HVMztjo2K8Hg==}
+ /@typescript-eslint/[email protected](@typescript-eslint/[email protected])([email protected])([email protected]):
+ resolution: {integrity: sha512-oy9+hTPCUFpngkEZUSzbf9MxI65wbKFoQYsgPdILTfbUldp5ovUuphZVe4i30emU9M/kP+T64Di0mxl7dSw3MA==}
engines: {node: ^16.0.0 || >=18.0.0}
peerDependencies:
'@typescript-eslint/parser': ^6.0.0 || ^6.0.0-alpha
@@ -5740,10 +5746,10 @@ packages:
dependencies:
'@eslint-community/regexpp': 4.10.0
'@typescript-eslint/parser': 6.20.0([email protected])([email protected])
- '@typescript-eslint/scope-manager': 6.20.0
- '@typescript-eslint/type-utils': 6.20.0([email protected])([email protected])
- '@typescript-eslint/utils': 6.20.0([email protected])([email protected])
- '@typescript-eslint/visitor-keys': 6.20.0
+ '@typescript-eslint/scope-manager': 6.21.0
+ '@typescript-eslint/type-utils': 6.21.0([email protected])([email protected])
+ '@typescript-eslint/utils': 6.21.0([email protected])([email protected])
+ '@typescript-eslint/visitor-keys': 6.21.0
debug: 4.3.4
eslint: 8.56.0
graphemer: 1.4.0
@@ -5814,6 +5820,14 @@ packages:
'@typescript-eslint/visitor-keys': 6.20.0
dev: true
+ /@typescript-eslint/[email protected]:
+ resolution: {integrity: sha512-OwLUIWZJry80O99zvqXVEioyniJMa+d2GrqpUTqi5/v5D5rOrppJVBPa0yKCblcigC0/aYAzxxqQ1B+DS2RYsg==}
+ engines: {node: ^16.0.0 || >=18.0.0}
+ dependencies:
+ '@typescript-eslint/types': 6.21.0
+ '@typescript-eslint/visitor-keys': 6.21.0
+ dev: true
+
/@typescript-eslint/[email protected]:
resolution: {integrity: sha512-v7/T7As10g3bcWOOPAcbnMDuvctHzCFYCG/8R4bK4iYzdFqsZTbXGln0cZNVcwQcwewsYU2BJLay8j0/4zOk4w==}
engines: {node: ^16.0.0 || >=18.0.0}
@@ -5822,8 +5836,8 @@ packages:
'@typescript-eslint/visitor-keys': 7.0.1
dev: true
- resolution: {integrity: sha512-qnSobiJQb1F5JjN0YDRPHruQTrX7ICsmltXhkV536mp4idGAYrIyr47zF/JmkJtEcAVnIz4gUYJ7gOZa6SmN4g==}
+ resolution: {integrity: sha512-rZQI7wHfao8qMX3Rd3xqeYSMCL3SoiSQLBATSiVKARdFGCYSRvmViieZjqc58jKgs8Y8i9YvVVhRbHSTA4VBag==}
engines: {node: ^16.0.0 || >=18.0.0}
peerDependencies:
eslint: ^7.0.0 || ^8.0.0
@@ -5832,8 +5846,8 @@ packages:
typescript:
optional: true
dependencies:
- '@typescript-eslint/typescript-estree': 6.20.0([email protected])
- '@typescript-eslint/utils': 6.20.0([email protected])([email protected])
+ '@typescript-eslint/typescript-estree': 6.21.0([email protected])
+ '@typescript-eslint/utils': 6.21.0([email protected])([email protected])
debug: 4.3.4
eslint: 8.56.0
ts-api-utils: 1.0.3([email protected])
@@ -5852,6 +5866,11 @@ packages:
engines: {node: ^16.0.0 || >=18.0.0}
dev: true
+ /@typescript-eslint/[email protected]:
+ resolution: {integrity: sha512-1kFmZ1rOm5epu9NZEZm1kckCDGj5UJEf7P1kliH4LKu/RkwpsfqqGmY2OOcUs18lSlQBKLDYBOGxRVtrMN5lpg==}
+ engines: {node: ^16.0.0 || >=18.0.0}
+ dev: true
+
/@typescript-eslint/[email protected]:
resolution: {integrity: sha512-uJDfmirz4FHib6ENju/7cz9SdMSkeVvJDK3VcMFvf/hAShg8C74FW+06MaQPODHfDJp/z/zHfgawIJRjlu0RLg==}
engines: {node: ^16.0.0 || >=18.0.0}
@@ -5901,6 +5920,28 @@ packages:
- supports-color
dev: true
+ /@typescript-eslint/[email protected]([email protected]):
+ resolution: {integrity: sha512-6npJTkZcO+y2/kr+z0hc4HwNfrrP4kNYh57ek7yCNlrBjWQ1Y0OS7jiZTkgumrvkX5HkEKXFZkkdFNkaW2wmUQ==}
+ engines: {node: ^16.0.0 || >=18.0.0}
+ peerDependencies:
+ typescript: '*'
+ peerDependenciesMeta:
+ typescript:
+ optional: true
+ dependencies:
+ '@typescript-eslint/types': 6.21.0
+ '@typescript-eslint/visitor-keys': 6.21.0
+ debug: 4.3.4
+ globby: 11.1.0
+ is-glob: 4.0.3
+ minimatch: 9.0.3
+ semver: 7.5.4
+ ts-api-utils: 1.0.3([email protected])
+ typescript: 5.3.3
+ transitivePeerDependencies:
+ - supports-color
+ dev: true
+
/@typescript-eslint/[email protected]([email protected]):
resolution: {integrity: sha512-SO9wHb6ph0/FN5OJxH4MiPscGah5wjOd0RRpaLvuBv9g8565Fgu0uMySFEPqwPHiQU90yzJ2FjRYKGrAhS1xig==}
engines: {node: ^16.0.0 || >=18.0.0}
@@ -5942,8 +5983,8 @@ packages:
- typescript
dev: true
- resolution: {integrity: sha512-/EKuw+kRu2vAqCoDwDCBtDRU6CTKbUmwwI7SH7AashZ+W+7o8eiyy6V2cdOqN49KsTcASWsC5QeghYuRDTyOOg==}
+ resolution: {integrity: sha512-NfWVaC8HP9T8cbKQxHcsJBY5YE1O33+jpMwN45qzWWaPDZgLIbo12toGMWnmhvCpd3sIxkpDw3Wv1B3dYrbDQQ==}
engines: {node: ^16.0.0 || >=18.0.0}
peerDependencies:
eslint: ^7.0.0 || ^8.0.0
@@ -5951,9 +5992,9 @@ packages:
'@eslint-community/eslint-utils': 4.4.0([email protected])
'@types/json-schema': 7.0.15
'@types/semver': 7.5.6
- '@typescript-eslint/scope-manager': 6.20.0
- '@typescript-eslint/types': 6.20.0
- '@typescript-eslint/typescript-estree': 6.20.0([email protected])
+ '@typescript-eslint/scope-manager': 6.21.0
+ '@typescript-eslint/types': 6.21.0
+ '@typescript-eslint/typescript-estree': 6.21.0([email protected])
eslint: 8.56.0
semver: 7.6.0
transitivePeerDependencies:
@@ -5977,6 +6018,14 @@ packages:
eslint-visitor-keys: 3.4.3
dev: true
+ /@typescript-eslint/[email protected]:
+ resolution: {integrity: sha512-JJtkDduxLi9bivAB+cYOVMtbkqdPOhZ+ZI5LC47MIRrDV4Yn2o+ZnW10Nkmr28xRpSpdJ6Sm42Hjf2+REYXm0A==}
+ engines: {node: ^16.0.0 || >=18.0.0}
+ dependencies:
+ '@typescript-eslint/types': 6.21.0
+ eslint-visitor-keys: 3.4.3
+ dev: true
+
/@typescript-eslint/[email protected]:
resolution: {integrity: sha512-hwAgrOyk++RTXrP4KzCg7zB2U0xt7RUU0ZdMSCsqF3eKUwkdXUMyTb0qdCuji7VIbcpG62kKTU9M1J1c9UpFBw==}
engines: {node: ^16.0.0 || >=18.0.0}
@@ -8299,8 +8348,8 @@ packages:
- supports-color
dev: true
- resolution: {integrity: sha512-A0cH+5svWPXzGZszBjXA1t0aAqVGS+/x3i02KFmb73rU0iMLnadEcVWcD/dGBZHIfAMKr3YpWh58f6wn4N909w==}
+ resolution: {integrity: sha512-9ZYb3W6r6nZ3jc9vmJ2pZoINLhk9iI6rEFTfU7sTRAzFUWh00SRI9SRZ+IgDoiIPTp2tOUXs0vDOApdIlTnFKA==}
engines: {node: '>=18'}
peerDependencies:
eslint: ^7.0.0 || ^8.0.0 || ^9.0.0
@@ -8484,7 +8533,7 @@ packages:
- supports-color
dev: true
resolution: {integrity: sha512-sduiswLJfZHeeBJ+MQaG+xYzSWdRXoSw61DpU13mzWumCkR0ufD0HmO4kdNokjrkluMHpj/7PJeN35pgbhW3kw==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
peerDependencies:
@@ -8494,12 +8543,12 @@ packages:
'@typescript-eslint/eslint-plugin':
optional: true
dependencies:
- '@typescript-eslint/eslint-plugin': 6.20.0(@typescript-eslint/[email protected])([email protected])([email protected])
+ '@typescript-eslint/eslint-plugin': 6.21.0(@typescript-eslint/[email protected])([email protected])([email protected])
eslint: 8.56.0
eslint-rule-composer: 0.3.0
dev: true
resolution: {integrity: sha512-oYwR1MrwaBw/OG6CKU+SJYleAc442w6CWL1RTQl5WLwy8X3sh0bgHIQk5iEtmTak3Q+XAvZglr0bIoDOjFdkcw==}
engines: {node: ^18.0.0 || >= 20.0.0}
peerDependencies:
@@ -8512,8 +8561,8 @@ packages:
vitest:
optional: true
dependencies:
- '@typescript-eslint/eslint-plugin': 6.20.0(@typescript-eslint/[email protected])([email protected])([email protected])
- '@typescript-eslint/utils': 6.20.0([email protected])([email protected])
+ '@typescript-eslint/eslint-plugin': 6.21.0(@typescript-eslint/[email protected])([email protected])([email protected])
+ '@typescript-eslint/utils': 6.21.0([email protected])([email protected])
eslint: 8.56.0
transitivePeerDependencies:
- supports-color
@@ -13036,7 +13085,6 @@ packages:
hasBin: true
dependencies:
lru-cache: 6.0.0
- dev: false
resolution: {integrity: sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==}