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: add formula error handling in f-workbook and f-range mixin (#5761)

Dushusirb2cf32f6c09a
diff --git a/packages/engine-formula/src/basics/error-type.ts b/packages/engine-formula/src/basics/error-type.ts
index c5d940fb9c..f4a4350dff 100644
--- a/packages/engine-formula/src/basics/error-type.ts
+++ b/packages/engine-formula/src/basics/error-type.ts
@@ -49,3 +49,21 @@ export enum ErrorType {
export const ERROR_TYPE_SET = new Set(Object.values(ErrorType));
export const ERROR_TYPE_COUNT_ARRAY = [...new Set(Object.values(ErrorType).map((error) => error.length))];
+
+/** Interface for sheet formula errors */
+export interface ISheetFormulaError {
+ /** sheet name */
+ sheetName: string;
+
+ /** cell row */
+ row: number;
+
+ /** cell column */
+ column: number;
+
+ /** formula string (e.g., "=SUM(A1:B10)") */
+ formula: string;
+
+ /** error type, refer to ErrorType enum */
+ errorType: ErrorType;
+}
diff --git a/packages/engine-formula/src/engine/utils/__tests__/cell.spec.ts b/packages/engine-formula/src/engine/utils/__tests__/cell.spec.ts
index 2beb075adb..4ad09b6b9e 100644
--- a/packages/engine-formula/src/engine/utils/__tests__/cell.spec.ts
+++ b/packages/engine-formula/src/engine/utils/__tests__/cell.spec.ts
@@ -16,7 +16,8 @@
import type { ICellData } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
-import { getCellValue } from '../cell';
+import { ErrorType } from '../../../basics/error-type';
+import { extractFormulaError, getCellValue } from '../cell';
describe('Test cell', () => {
it('Function getCellValue', () => {
@@ -42,4 +43,32 @@ describe('Test cell', () => {
expect(getCellValue(cell2)).toBe(2);
expect(getCellValue(cell3)).toBe(0);
});
+
+ it('Function extractFormulaError', () => {
+ expect(extractFormulaError({ v: ErrorType.DIV_BY_ZERO, f: '=1/0' })).toBe(ErrorType.DIV_BY_ZERO);
+ expect(extractFormulaError({ v: ErrorType.NAME, f: '=S' })).toBe(ErrorType.NAME);
+ expect(extractFormulaError({ v: ErrorType.VALUE, f: '=SUM(A1)' })).toBe(ErrorType.VALUE);
+ expect(extractFormulaError({ v: ErrorType.NUM, f: '=SUM(A1)' })).toBe(ErrorType.NUM);
+ expect(extractFormulaError({ v: ErrorType.NA, f: '=SUM(A1)' })).toBe(ErrorType.NA);
+ expect(extractFormulaError({ v: ErrorType.CYCLE, f: '=SUM(A1)' })).toBe(ErrorType.CYCLE);
+ expect(extractFormulaError({ v: ErrorType.REF, f: '=SUM(A1)' })).toBe(ErrorType.REF);
+ expect(extractFormulaError({ v: ErrorType.SPILL, f: '=SUM(A1)' })).toBe(ErrorType.SPILL);
+ expect(extractFormulaError({ v: ErrorType.CALC, f: '=SUM(A1)' })).toBe(ErrorType.CALC);
+ expect(extractFormulaError({ v: ErrorType.ERROR, f: '=SUM(A1)' })).toBe(ErrorType.ERROR);
+ expect(extractFormulaError({ v: ErrorType.CONNECT, f: '=SUM(A1)' })).toBe(ErrorType.CONNECT);
+
+ expect(extractFormulaError({ v: ErrorType.NULL, f: '=SUM(A1)' })).toBe(ErrorType.NULL);
+ expect(extractFormulaError({ v: ErrorType.NULL, f: '=SUM(A1)', si: 'id1' })).toBe(ErrorType.NULL);
+ expect(extractFormulaError({ v: ErrorType.NULL, si: 'id1' })).toBe(ErrorType.NULL);
+ expect(extractFormulaError({ v: ErrorType.NULL })).toBeNull();
+
+ expect(extractFormulaError({ f: '=SUM(1)' })).toBeNull();
+ expect(extractFormulaError({ si: 'id1' })).toBeNull();
+ expect(extractFormulaError({ p: null })).toBeNull();
+ expect(extractFormulaError({ v: 'test' })).toBeNull();
+ expect(extractFormulaError({ v: 1 })).toBeNull();
+ expect(extractFormulaError({})).toBeNull();
+ expect(extractFormulaError(null)).toBeNull();
+ expect(extractFormulaError(undefined)).toBeNull();
+ });
});
diff --git a/packages/engine-formula/src/engine/utils/cell.ts b/packages/engine-formula/src/engine/utils/cell.ts
index 9b194fa77f..f50ea81147 100644
--- a/packages/engine-formula/src/engine/utils/cell.ts
+++ b/packages/engine-formula/src/engine/utils/cell.ts
@@ -15,7 +15,9 @@
*/
import type { ICellData, Nullable } from '@univerjs/core';
-import { BuildTextUtils } from '@univerjs/core';
+import type { ErrorType } from '../../basics/error-type';
+import { BuildTextUtils, isFormulaId, isFormulaString } from '@univerjs/core';
+import { ERROR_TYPE_SET } from '../../basics/error-type';
export function getCellValue(cell: Nullable<ICellData>) {
if (cell === null) {
@@ -37,3 +39,21 @@ export function getCellValue(cell: Nullable<ICellData>) {
return cell?.v ?? 0;
}
+
+/**
+ * Extract the formula error from the cell
+ * @param cell
+ * @returns
+ */
+export function extractFormulaError(cell: Nullable<ICellData>, isArrayFormulaCell: boolean = false) {
+ // Must contain a formula
+ if (!isArrayFormulaCell && !(isFormulaString(cell?.f) || isFormulaId(cell?.si))) {
+ return null;
+ }
+
+ if (typeof cell?.v === 'string' && ERROR_TYPE_SET.has(cell.v as ErrorType)) {
+ return cell.v as ErrorType;
+ }
+
+ return null;
+}
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index d59b39646b..d48e1f68cd 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -35,6 +35,7 @@ export { type IOtherFormulaData } from './basics/common';
export { type IUnitRowData } from './basics/common';
export { isInDirtyRange } from './basics/dirty';
export { ERROR_TYPE_SET, ErrorType } from './basics/error-type';
+export { type ISheetFormulaError } from './basics/error-type';
export { FunctionType, type IFunctionInfo, type IFunctionParam } from './basics/function';
export { type IFunctionNames } from './basics/function';
export { includeFormulaLexerToken, isFormulaLexerToken, normalizeSheetName } from './basics/match-token';
@@ -86,6 +87,7 @@ export { BaseReferenceObject, type FunctionVariantType } from './engine/referenc
export { AsyncArrayObject, AsyncObject } from './engine/reference-object/base-reference-object';
export { RangeReferenceObject } from './engine/reference-object/range-reference-object';
export { generateExecuteAstNodeData } from './engine/utils/ast-node-tool';
+export { extractFormulaError } from './engine/utils/cell';
export { generateAstNode } from './engine/utils/generate-ast-node';
export { strip, stripErrorMargin } from './engine/utils/math-kit';
export { handleNumfmtInCell } from './engine/utils/numfmt-kit';
diff --git a/packages/sheets-formula-ui/src/controllers/formula-alert-render.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-alert-render.controller.ts
index aabe6705f1..38c2383674 100644
--- a/packages/sheets-formula-ui/src/controllers/formula-alert-render.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/formula-alert-render.controller.ts
@@ -17,11 +17,10 @@
import type { Workbook } from '@univerjs/core';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
import { Disposable, Inject, isICellData, LocaleService } from '@univerjs/core';
-import { ErrorType, FormulaDataModel } from '@univerjs/engine-formula';
+import { ErrorType, extractFormulaError, FormulaDataModel } from '@univerjs/engine-formula';
import { CellAlertManagerService, CellAlertType, HoverManagerService } from '@univerjs/sheets-ui';
import { IZenZoneService } from '@univerjs/ui';
import { debounceTime } from 'rxjs';
-import { extractFormulaError } from './utils/utils';
const ALERT_KEY = 'SHEET_FORMULA_ALERT';
diff --git a/packages/sheets-formula-ui/src/controllers/formula-render.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-render.controller.ts
index 714f80e9c3..2323055d4d 100644
--- a/packages/sheets-formula-ui/src/controllers/formula-render.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/formula-render.controller.ts
@@ -15,9 +15,8 @@
*/
import { Inject, InterceptorEffectEnum, RxDisposable } from '@univerjs/core';
-import { FormulaDataModel } from '@univerjs/engine-formula';
+import { extractFormulaError, FormulaDataModel } from '@univerjs/engine-formula';
import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
-import { extractFormulaError } from './utils/utils';
const FORMULA_ERROR_MARK = {
tl: {
diff --git a/packages/sheets-formula-ui/src/controllers/utils/__tests__/utils.spec.ts b/packages/sheets-formula-ui/src/controllers/utils/__tests__/utils.spec.ts
index dba7235f22..d510a1a316 100644
--- a/packages/sheets-formula-ui/src/controllers/utils/__tests__/utils.spec.ts
+++ b/packages/sheets-formula-ui/src/controllers/utils/__tests__/utils.spec.ts
@@ -16,39 +16,10 @@
import { CellValueType } from '@univerjs/core';
-import { ErrorType } from '@univerjs/engine-formula';
import { describe, expect, it } from 'vitest';
-import { extractFormulaError, extractFormulaNumber } from '../utils';
+import { extractFormulaNumber } from '../utils';
describe('Test utils', () => {
- it('Function extractFormulaError', () => {
- expect(extractFormulaError({ v: ErrorType.DIV_BY_ZERO, f: '=1/0' })).toBe(ErrorType.DIV_BY_ZERO);
- expect(extractFormulaError({ v: ErrorType.NAME, f: '=S' })).toBe(ErrorType.NAME);
- expect(extractFormulaError({ v: ErrorType.VALUE, f: '=SUM(A1)' })).toBe(ErrorType.VALUE);
- expect(extractFormulaError({ v: ErrorType.NUM, f: '=SUM(A1)' })).toBe(ErrorType.NUM);
- expect(extractFormulaError({ v: ErrorType.NA, f: '=SUM(A1)' })).toBe(ErrorType.NA);
- expect(extractFormulaError({ v: ErrorType.CYCLE, f: '=SUM(A1)' })).toBe(ErrorType.CYCLE);
- expect(extractFormulaError({ v: ErrorType.REF, f: '=SUM(A1)' })).toBe(ErrorType.REF);
- expect(extractFormulaError({ v: ErrorType.SPILL, f: '=SUM(A1)' })).toBe(ErrorType.SPILL);
- expect(extractFormulaError({ v: ErrorType.CALC, f: '=SUM(A1)' })).toBe(ErrorType.CALC);
- expect(extractFormulaError({ v: ErrorType.ERROR, f: '=SUM(A1)' })).toBe(ErrorType.ERROR);
- expect(extractFormulaError({ v: ErrorType.CONNECT, f: '=SUM(A1)' })).toBe(ErrorType.CONNECT);
-
- expect(extractFormulaError({ v: ErrorType.NULL, f: '=SUM(A1)' })).toBe(ErrorType.NULL);
- expect(extractFormulaError({ v: ErrorType.NULL, f: '=SUM(A1)', si: 'id1' })).toBe(ErrorType.NULL);
- expect(extractFormulaError({ v: ErrorType.NULL, si: 'id1' })).toBe(ErrorType.NULL);
- expect(extractFormulaError({ v: ErrorType.NULL })).toBeNull();
-
- expect(extractFormulaError({ f: '=SUM(1)' })).toBeNull();
- expect(extractFormulaError({ si: 'id1' })).toBeNull();
- expect(extractFormulaError({ p: null })).toBeNull();
- expect(extractFormulaError({ v: 'test' })).toBeNull();
- expect(extractFormulaError({ v: 1 })).toBeNull();
- expect(extractFormulaError({})).toBeNull();
- expect(extractFormulaError(null)).toBeNull();
- expect(extractFormulaError(undefined)).toBeNull();
- });
-
it('Function extractFormulaNumber', () => {
const v = 0.07 / 0.1;
expect(extractFormulaNumber({ v })).toBeNull();
diff --git a/packages/sheets-formula-ui/src/controllers/utils/utils.ts b/packages/sheets-formula-ui/src/controllers/utils/utils.ts
index e04c24b977..cc3413aa37 100644
--- a/packages/sheets-formula-ui/src/controllers/utils/utils.ts
+++ b/packages/sheets-formula-ui/src/controllers/utils/utils.ts
@@ -15,9 +15,8 @@
*/
import type { ICellData, IContextService, Nullable } from '@univerjs/core';
-import type { ErrorType } from '@univerjs/engine-formula';
import { CellValueType, FOCUSING_DOC, FOCUSING_UNIVER_EDITOR, isFormulaId, isFormulaString } from '@univerjs/core';
-import { ERROR_TYPE_SET, stripErrorMargin } from '@univerjs/engine-formula';
+import { stripErrorMargin } from '@univerjs/engine-formula';
export function whenEditorStandalone(contextService: IContextService) {
return (
@@ -28,24 +27,6 @@ export function whenEditorStandalone(contextService: IContextService) {
);
}
-/**
- * Extract the formula error from the cell
- * @param cell
- * @returns
- */
-export function extractFormulaError(cell: Nullable<ICellData>, isArrayFormulaCell: boolean = false) {
- // Must contain a formula
- if (!isArrayFormulaCell && !(isFormulaString(cell?.f) || isFormulaId(cell?.si))) {
- return null;
- }
-
- if (typeof cell?.v === 'string' && ERROR_TYPE_SET.has(cell.v as ErrorType)) {
- return cell.v as ErrorType;
- }
-
- return null;
-}
-
/**
* Extract the formula number from the cell, handle the precision issue
* @param cell
diff --git a/packages/sheets-formula/package.json b/packages/sheets-formula/package.json
index a27abaad1c..85edeba887 100644
--- a/packages/sheets-formula/package.json
+++ b/packages/sheets-formula/package.json
@@ -79,6 +79,7 @@
"dependencies": {
"@univerjs/core": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
+ "@univerjs/engine-render": "workspace:*",
"@univerjs/rpc": "workspace:*",
"@univerjs/sheets": "workspace:*"
},
diff --git a/packages/sheets-formula/src/facade/__tests__/create-test-bed.ts b/packages/sheets-formula/src/facade/__tests__/create-test-bed.ts
new file mode 100644
index 0000000000..174f6459a0
--- /dev/null
+++ b/packages/sheets-formula/src/facade/__tests__/create-test-bed.ts
@@ -0,0 +1,193 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * 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 { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';
+import type { IRender } from '@univerjs/engine-render';
+import {
+ ILogService,
+ Inject,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ LogLevel,
+ Plugin,
+ set,
+ ThemeService,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { FUniver } from '@univerjs/core/facade';
+import { DefinedNamesService, FormulaDataModel, FunctionService, IDefinedNamesService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';
+import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
+import {
+ RangeProtectionRuleModel,
+ RefRangeService,
+ SheetInterceptorService,
+ SheetSkeletonService,
+ SheetsSelectionsService,
+ WorkbookPermissionService,
+ WorksheetPermissionService,
+ WorksheetProtectionPointModel,
+ WorksheetProtectionRuleModel,
+} from '@univerjs/sheets';
+import enUS from '@univerjs/sheets/locale/en-US';
+import zhCN from '@univerjs/sheets/locale/zh-CN';
+
+import '@univerjs/sheets/facade';
+import '../f-workbook';
+import '../f-range';
+
+function getTestWorkbookDataDemo(): IWorkbookData {
+ return {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'sheet1',
+ cellData: {
+ 0: {
+ 3: {
+ f: '=SUM(A1)',
+ si: '3e4r5t',
+ },
+ 4: {
+ v: 123,
+ t: 2,
+ },
+ },
+ 1: {
+ 3: {
+ f: '=SUM(A2)',
+ si: 'OSPtzm',
+ },
+ },
+ 2: {
+ 3: {
+ si: 'OSPtzm',
+ },
+ },
+ 3: {
+ 3: {
+ si: 'OSPtzm',
+ },
+ },
+ },
+ rowCount: 100,
+ columnCount: 100,
+ },
+ },
+ locale: LocaleType.ZH_CN,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+ };
+}
+
+export interface ITestBed {
+ univer: Univer;
+ get: Injector['get'];
+ sheet: UnitModel<IWorkbookData>;
+ univerAPI: FUniver;
+ injector: Injector;
+}
+
+class RenderManagerServiceTestBed extends RenderManagerService {
+ override createRender(unitId: string): IRender {
+ const renderer = this._createRender(unitId, new Engine('', { elementHeight: 100, elementWidth: 100 }));
+ return renderer;
+ }
+}
+
+export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]): ITestBed {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+
+ class TestPlugin extends Plugin {
+ static override pluginName = 'test-plugin';
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(): void {
+ const injector = this._injector;
+ injector.add([SheetsSelectionsService]);
+ injector.add([SheetInterceptorService]);
+
+ injector.add([IFunctionService, { useClass: FunctionService }]);
+ injector.add([IRenderingEngine, { useFactory: () => new Engine() }]);
+ injector.add([IRenderManagerService, { useClass: RenderManagerServiceTestBed }]);
+ injector.add([SheetSkeletonService]);
+ injector.add([FormulaDataModel]);
+ injector.add([LexerTreeBuilder]);
+ injector.add([RefRangeService]);
+ injector.add([WorksheetPermissionService]);
+ injector.add([WorkbookPermissionService]);
+ injector.add([WorksheetProtectionPointModel]);
+ injector.add([RangeProtectionRuleModel]);
+ injector.add([WorksheetProtectionRuleModel]);
+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);
+
+ dependencies?.forEach((d) => injector.add(d));
+
+ this._injector.get(SheetInterceptorService);
+ this._injector.get(WorkbookPermissionService);
+ this._injector.get(WorksheetPermissionService);
+ }
+
+ override onReady(): void {
+
+ }
+ }
+
+ // load i18n
+ injector.get(LocaleService).load({ zhCN, enUS });
+
+ // load theme service
+ const themeService = injector.get(ThemeService);
+ const theme = themeService.getCurrentTheme();
+ const newTheme = set(theme, 'black', '#35322b');
+ themeService.setTheme(newTheme);
+
+ // register builtin plugins
+ // note that UI plugins are not registered here, because the unit test environment does not have a UI
+ univer.registerPlugin(TestPlugin);
+
+ const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, workbookData || getTestWorkbookDataDemo());
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ univerInstanceService.focusUnit('test');
+
+ // set log level
+ const logService = injector.get(ILogService);
+ logService.setLogLevel(LogLevel.SILENT); // NOTE: change this to `LogLevel.VERBOSE` to debug tests via logs
+
+ // init data validation
+ const univerAPI = FUniver.newAPI(injector);
+
+ return {
+ univer,
+ get: injector.get.bind(injector),
+ sheet,
+ univerAPI,
+ injector,
+ };
+}
diff --git a/packages/sheets-formula/src/facade/__tests__/f-range-engine-formula.spec.ts b/packages/sheets-formula/src/facade/__tests__/f-range-engine-formula.spec.ts
new file mode 100644
index 0000000000..b7def52fa3
--- /dev/null
+++ b/packages/sheets-formula/src/facade/__tests__/f-range-engine-formula.spec.ts
@@ -0,0 +1,291 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * 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, IWorkbookData } from '@univerjs/core';
+import type { FUniver } from '@univerjs/core/facade';
+import { ICommandService, LocaleType } from '@univerjs/core';
+import { ErrorType } from '@univerjs/engine-formula';
+import { SetRangeValuesCommand, SetRangeValuesMutation } from '@univerjs/sheets';
+import { beforeEach, describe, expect, it } from 'vitest';
+import { createFacadeTestBed } from './create-test-bed';
+
+function getTestWorkbookDataWithFormulas(): IWorkbookData {
+ return {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'sheet1',
+ cellData: {
+ 0: {
+ 0: {
+ v: 1,
+ },
+ 1: {
+ v: 2,
+ },
+ 2: {
+ f: '=SUM(A1:B1)',
+ v: 3,
+ },
+ 3: {
+ f: '=A1/0',
+ v: ErrorType.DIV_BY_ZERO,
+ t: 4,
+ },
+ },
+ 1: {
+ 0: {
+ f: '=UNKNOWN_FUNCTION()',
+ v: ErrorType.NAME,
+ t: 4,
+ },
+ 1: {
+ f: '=SUM(A1,A2)',
+ v: 2,
+ },
+ 2: {
+ f: '=SQRT(-1)',
+ v: ErrorType.NUM,
+ t: 4,
+ },
+ },
+ 2: {
+ 0: {
+ v: 'text',
+ },
+ 1: {
+ f: '=A3+B2',
+ v: ErrorType.VALUE,
+ t: 4,
+ },
+ 2: {
+ v: 'normal text',
+ },
+ },
+ 3: {
+ 0: {
+ v: 10,
+ },
+ 1: {
+ v: 20,
+ },
+ 2: {
+ f: '=A4+B4',
+ v: 30,
+ },
+ },
+ },
+ rowCount: 100,
+ columnCount: 100,
+ },
+ },
+ locale: LocaleType.ZH_CN,
+ name: 'Test Workbook',
+ sheetOrder: ['sheet1'],
+ styles: {},
+ };
+}
+
+describe('Test FRangeEngineFormulaMixin', () => {
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let univerAPI: FUniver;
+
+ beforeEach(() => {
+ const testBed = createFacadeTestBed(getTestWorkbookDataWithFormulas());
+ get = testBed.get;
+ univerAPI = testBed.univerAPI;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(SetRangeValuesCommand);
+ commandService.registerCommand(SetRangeValuesMutation);
+ });
+
+ it('should get formula errors in a specific range', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet()!;
+
+ // Test range that contains errors (A1:D2)
+ const range = worksheet.getRange('A1:D2');
+ const errors = range.getFormulaError();
+
+ expect(errors).toBeDefined();
+ expect(Array.isArray(errors)).toBe(true);
+ expect(errors.length).toBeGreaterThan(0);
+
+ // Check for specific error types in this range
+ const divByZeroErrors = errors.filter((e) => e.errorType === ErrorType.DIV_BY_ZERO);
+ const nameErrors = errors.filter((e) => e.errorType === ErrorType.NAME);
+ const numErrors = errors.filter((e) => e.errorType === ErrorType.NUM);
+
+ expect(divByZeroErrors.length).toBe(1);
+ expect(nameErrors.length).toBe(1);
+ expect(numErrors.length).toBe(1);
+
+ // All errors should be within the specified range
+ errors.forEach((error) => {
+ expect(error.row >= 0).toBe(true);
+ expect(error.row <= 1).toBe(true);
+ expect(error.column >= 0).toBe(true);
+ expect(error.column <= 3).toBe(true);
+ expect(error.sheetName).toBe('sheet1');
+ });
+ });
+
+ it('should return empty array for range with no formula errors', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet()!;
+
+ // Test range that contains no errors (A1:B1 - only regular values)
+ const range = worksheet.getRange('A1:B1');
+ const errors = range.getFormulaError();
+
+ expect(errors).toBeDefined();
+ expect(Array.isArray(errors)).toBe(true);
+ expect(errors.length).toBe(0);
+ });
+
+ it('should get formula errors in a single cell range', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet()!;
+
+ // Test single cell with error (D1 contains DIV_BY_ZERO error)
+ const range = worksheet.getRange('D1');
+ const errors = range.getFormulaError();
+
+ expect(errors).toBeDefined();
+ expect(Array.isArray(errors)).toBe(true);
+ expect(errors.length).toBe(1);
+
+ const error = errors[0];
+ expect(error.errorType).toBe(ErrorType.DIV_BY_ZERO);
+ expect(error.row).toBe(0);
+ expect(error.column).toBe(3);
+ expect(error.formula).toBe('=A1/0');
+ expect(error.sheetName).toBe('sheet1');
+ });
+
+ it('should handle range with mixed content (errors and normal values)', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet()!;
+
+ // Test range that contains both errors and normal values (A1:C3)
+ const range = worksheet.getRange('A1:C3');
+ const errors = range.getFormulaError();
+
+ expect(errors).toBeDefined();
+ expect(Array.isArray(errors)).toBe(true);
+ expect(errors.length).toBe(3); // Should find VALUE and NUM errors
+
+ const errorTypes = new Set(errors.map((e) => e.errorType));
+ expect(errorTypes.has(ErrorType.NAME)).toBe(true);
+ expect(errorTypes.has(ErrorType.VALUE)).toBe(true);
+ expect(errorTypes.has(ErrorType.NUM)).toBe(true);
+ });
+
+ it('should validate error object properties', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet()!;
+
+ // Test range with known error
+ const range = worksheet.getRange('A2:C2');
+ const errors = range.getFormulaError();
+
+ expect(errors.length).toBeGreaterThan(0);
+
+ errors.forEach((error) => {
+ expect(error).toHaveProperty('sheetName');
+ expect(error).toHaveProperty('row');
+ expect(error).toHaveProperty('column');
+ expect(error).toHaveProperty('formula');
+ expect(error).toHaveProperty('errorType');
+
+ expect(typeof error.sheetName).toBe('string');
+ expect(typeof error.row).toBe('number');
+ expect(typeof error.column).toBe('number');
+ expect(typeof error.formula).toBe('string');
+ expect(typeof error.errorType).toBe('string');
+
+ expect(error.sheetName).toBe('sheet1');
+ expect(error.row >= 1).toBe(true);
+ expect(error.row <= 1).toBe(true);
+ expect(error.column >= 0).toBe(true);
+ expect(error.column <= 2).toBe(true);
+ expect(error.formula.startsWith('=')).toBe(true);
+ });
+ });
+
+ it('should return empty array for range with only normal formulas', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet()!;
+
+ // Test range that contains normal formulas without errors (A4:C4)
+ const range = worksheet.getRange('A4:C4');
+ const errors = range.getFormulaError();
+
+ expect(errors).toBeDefined();
+ expect(Array.isArray(errors)).toBe(true);
+ expect(errors.length).toBe(0);
+ });
+
+ it('should handle large range correctly', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet()!;
+
+ // Test large range that includes all test data
+ const range = worksheet.getRange('A1:Z100');
+ const errors = range.getFormulaError();
+
+ expect(errors).toBeDefined();
+ expect(Array.isArray(errors)).toBe(true);
+
+ // Should find all the errors in the worksheet
+ const errorTypes = new Set(errors.map((e) => e.errorType));
+ expect(errorTypes.has(ErrorType.DIV_BY_ZERO)).toBe(true);
+ expect(errorTypes.has(ErrorType.NAME)).toBe(true);
+ expect(errorTypes.has(ErrorType.NUM)).toBe(true);
+ expect(errorTypes.has(ErrorType.VALUE)).toBe(true);
+ });
+
+ it('should identify different error types correctly in range', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet()!;
+
+ // Test range containing different error types
+ const range = worksheet.getRange('A1:D3');
+ const errors = range.getFormulaError();
+
+ const errorsByType: Partial<Record<ErrorType, number>> = {
+ [ErrorType.DIV_BY_ZERO]: 0,
+ [ErrorType.NAME]: 0,
+ [ErrorType.NUM]: 0,
+ [ErrorType.VALUE]: 0,
+ };
+
+ errors.forEach((error) => {
+ if (error.errorType in errorsByType) {
+ errorsByType[error.errorType] = (errorsByType[error.errorType] || 0) + 1;
+ }
+ });
+
+ expect(errorsByType[ErrorType.DIV_BY_ZERO]).toBe(1);
+ expect(errorsByType[ErrorType.NAME]).toBe(1);
+ expect(errorsByType[ErrorType.NUM]).toBe(1);
+ expect(errorsByType[ErrorType.VALUE]).toBe(1);
+ });
+});
diff --git a/packages/sheets-formula/src/facade/__tests__/f-workbook-engine-formula.spec.ts b/packages/sheets-formula/src/facade/__tests__/f-workbook-engine-formula.spec.ts
new file mode 100644
index 0000000000..a9dffa5062
--- /dev/null
+++ b/packages/sheets-formula/src/facade/__tests__/f-workbook-engine-formula.spec.ts
@@ -0,0 +1,196 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * 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, IWorkbookData } from '@univerjs/core';
+import type { FUniver } from '@univerjs/core/facade';
+import { ICommandService, LocaleType } from '@univerjs/core';
+import { ErrorType } from '@univerjs/engine-formula';
+import { SetRangeValuesCommand, SetRangeValuesMutation } from '@univerjs/sheets';
+import { beforeEach, describe, expect, it } from 'vitest';
+import { createFacadeTestBed } from './create-test-bed';
+
+function getTestWorkbookDataWithFormulas(): IWorkbookData {
+ return {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'sheet1',
+ cellData: {
+ 0: {
+ 0: {
+ v: 1,
+ },
+ 1: {
+ v: 2,
+ },
+ 2: {
+ f: '=SUM(A1:B1)',
+ v: 3,
+ },
+ 3: {
+ f: '=A1/0',
+ v: ErrorType.DIV_BY_ZERO,
+ t: 4,
+ },
+ },
+ 1: {
+ 0: {
+ f: '=UNKNOWN_FUNCTION()',
+
+ v: ErrorType.NAME,
+ t: 4,
+
+ },
+ 1: {
+ f: '=SUM(A1,A2)',
+ v: 2,
+ },
+ 2: {
+ f: '=SQRT(-1)',
+
+ v: ErrorType.NUM,
+ t: 4,
+
+ },
+ },
+ 2: {
+ 0: {
+ v: 'text',
+ },
+ 1: {
+ f: '=A3+B2',
+
+ v: ErrorType.VALUE,
+ t: 4,
+
+ },
+ },
+ },
+ rowCount: 100,
+ columnCount: 100,
+ },
+ sheet2: {
+ id: 'sheet2',
+ name: 'sheet2',
+ cellData: {
+ 0: {
+ 0: {
+ f: '=1/0',
+ v: ErrorType.DIV_BY_ZERO,
+ t: 4,
+ },
+ },
+ },
+ rowCount: 100,
+ columnCount: 100,
+ },
+ },
+ locale: LocaleType.ZH_CN,
+ name: 'Test Workbook',
+ sheetOrder: ['sheet1', 'sheet2'],
+ styles: {},
+ };
+}
+
+describe('Test FWorkbookEngineFormulaMixin', () => {
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let univerAPI: FUniver;
+
+ beforeEach(() => {
+ const testBed = createFacadeTestBed(getTestWorkbookDataWithFormulas());
+ get = testBed.get;
+ univerAPI = testBed.univerAPI;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(SetRangeValuesCommand);
+ commandService.registerCommand(SetRangeValuesMutation);
+ });
+
+ it('should get all formula errors in the workbook', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const errors = workbook.getAllFormulaError();
+
+ expect(errors).toBeDefined();
+ expect(Array.isArray(errors)).toBe(true);
+ expect(errors.length).toBeGreaterThan(0);
+
+ // Check for specific error types
+ const divByZeroErrors = errors.filter((e) => e.errorType === ErrorType.DIV_BY_ZERO);
+ const nameErrors = errors.filter((e) => e.errorType === ErrorType.NAME);
+ const numErrors = errors.filter((e) => e.errorType === ErrorType.NUM);
+ const valueErrors = errors.filter((e) => e.errorType === ErrorType.VALUE);
+
+ expect(divByZeroErrors.length).toBeGreaterThan(0);
+ expect(nameErrors.length).toBeGreaterThan(0);
+ expect(numErrors.length).toBeGreaterThan(0);
+ expect(valueErrors.length).toBeGreaterThan(0);
+
+ // Check error details
+ const firstError = errors[0];
+ expect(firstError).toHaveProperty('sheetName');
+ expect(firstError).toHaveProperty('row');
+ expect(firstError).toHaveProperty('column');
+ expect(firstError).toHaveProperty('formula');
+ expect(firstError).toHaveProperty('errorType');
+ expect(typeof firstError.sheetName).toBe('string');
+ expect(typeof firstError.row).toBe('number');
+ expect(typeof firstError.column).toBe('number');
+ expect(typeof firstError.formula).toBe('string');
+ });
+
+ it('should identify different error types correctly', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const errors = workbook.getAllFormulaError();
+
+ const errorTypes = new Set(errors.map((e) => e.errorType));
+
+ // Should contain multiple error types from our test data
+ expect(errorTypes.has(ErrorType.DIV_BY_ZERO)).toBe(true);
+ expect(errorTypes.has(ErrorType.NAME)).toBe(true);
+ expect(errorTypes.has(ErrorType.NUM)).toBe(true);
+ expect(errorTypes.has(ErrorType.VALUE)).toBe(true);
+ });
+
+ it('should include correct formula strings in error results', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const errors = workbook.getAllFormulaError();
+
+ // Find specific errors and check their formula strings
+ const divByZeroError = errors.find((e) => e.errorType === ErrorType.DIV_BY_ZERO);
+ const nameError = errors.find((e) => e.errorType === ErrorType.NAME);
+
+ expect(divByZeroError).toBeDefined();
+ expect(divByZeroError!.formula).toContain('=');
+
+ expect(nameError).toBeDefined();
+ expect(nameError!.formula).toContain('=');
+ });
+
+ it('should find errors across multiple sheets', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const errors = workbook.getAllFormulaError();
+
+ const sheetNames = new Set(errors.map((e) => e.sheetName));
+
+ // Should find errors in both sheets
+ expect(sheetNames.has('sheet1')).toBe(true);
+ expect(sheetNames.has('sheet2')).toBe(true);
+ expect(sheetNames.size).toBe(2);
+ });
+});
diff --git a/packages/sheets-formula/src/facade/f-range.ts b/packages/sheets-formula/src/facade/f-range.ts
new file mode 100644
index 0000000000..3d81a6c37c
--- /dev/null
+++ b/packages/sheets-formula/src/facade/f-range.ts
@@ -0,0 +1,89 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * 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 { ISheetFormulaError } from '@univerjs/engine-formula';
+import { extractFormulaError, FormulaDataModel } from '@univerjs/engine-formula';
+import { FRange } from '@univerjs/sheets/facade';
+
+/**
+ * @ignore
+ */
+export interface IFRangeEngineFormulaMixin {
+ /**
+ * Get formula errors in the current range
+ * @returns {ISheetFormulaError[]} Array of formula errors in the range
+ * @example
+ * ```typescript
+ * const range = univerAPI.getActiveWorkbook()
+ * .getActiveSheet()
+ * .getRange('A1:B10');
+ * const errors = range.getFormulaError();
+ * console.log('Formula errors in range:', errors);
+ * ```
+ */
+ getFormulaError(): ISheetFormulaError[];
+}
+
+/**
+ * @ignore
+ */
+export class FRangeEngineFormulaMixin extends FRange implements IFRangeEngineFormulaMixin {
+ override getFormulaError(): ISheetFormulaError[] {
+ const errors: ISheetFormulaError[] = [];
+ const unitId = this._workbook.getUnitId();
+ const sheetId = this._worksheet.getSheetId();
+ const sheetName = this._worksheet.getName();
+ const worksheet = this._workbook.getSheetBySheetId(sheetId);
+
+ if (!worksheet) return errors;
+
+ const arrayFormula = this._injector.get(FormulaDataModel).getArrayFormulaCellData();
+ const arrayFormulaSheet = arrayFormula?.[unitId]?.[sheetId] || {};
+
+ const cellMatrix = worksheet.getCellMatrix();
+ const { startRow, endRow, startColumn, endColumn } = this._range;
+
+ // Traverse cells in the current range
+ for (let row = startRow; row <= endRow; row++) {
+ for (let column = startColumn; column <= endColumn; column++) {
+ const cell = cellMatrix.getValue(row, column);
+ if (!cell) continue;
+
+ const arrayFormulaCellData = arrayFormulaSheet?.[row]?.[column];
+ const errorType = extractFormulaError(cell, !!arrayFormulaCellData);
+
+ // Check if the cell value is an error
+ if (errorType) {
+ errors.push({
+ sheetName,
+ row,
+ column,
+ formula: cell.f || '',
+ errorType,
+ });
+ }
+ }
+ }
+
+ return errors;
+ }
+}
+
+FRange.extend(FRangeEngineFormulaMixin);
+declare module '@univerjs/sheets/facade' {
+ // eslint-disable-next-line ts/naming-convention
+ interface FRange extends IFRangeEngineFormulaMixin {}
+}
diff --git a/packages/sheets-formula/src/facade/f-workbook.ts b/packages/sheets-formula/src/facade/f-workbook.ts
new file mode 100644
index 0000000000..8d7ad4187b
--- /dev/null
+++ b/packages/sheets-formula/src/facade/f-workbook.ts
@@ -0,0 +1,82 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * 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 { ISheetFormulaError } from '@univerjs/engine-formula';
+import { extractFormulaError, FormulaDataModel } from '@univerjs/engine-formula';
+import { FWorkbook } from '@univerjs/sheets/facade';
+
+/**
+ * @ignore
+ */
+export interface IFWorkbookEngineFormulaMixin {
+ /**
+ * Get all formula errors in the workbook
+ * @returns {ISheetFormulaError[]} Array of formula errors
+ * @example
+ * ```typescript
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const errors = fWorkbook.getAllFormulaError();
+ * console.log('Formula errors:', errors);
+ * ```
+ */
+ getAllFormulaError(): ISheetFormulaError[];
+}
+
+export class FWorkbookEngineFormulaMixin extends FWorkbook implements IFWorkbookEngineFormulaMixin {
+ override getAllFormulaError(): ISheetFormulaError[] {
+ const errors: ISheetFormulaError[] = [];
+ const workbook = this._workbook;
+ const unitId = workbook.getUnitId();
+
+ // Get all worksheets in the workbook
+ const worksheets = workbook.getSheets();
+ const arrayFormula = this._injector.get(FormulaDataModel).getArrayFormulaCellData();
+
+ worksheets.forEach((worksheet) => {
+ const sheetName = worksheet.getName();
+ const sheetId = worksheet.getSheetId();
+ const cellMatrix = worksheet.getCellMatrix();
+ const arrayFormulaSheet = arrayFormula?.[unitId]?.[sheetId] || {};
+
+ // Traverse all cells in the worksheet
+ cellMatrix.forValue((row, column, cell) => {
+ if (!cell) return;
+
+ const arrayFormulaCellData = arrayFormulaSheet?.[row]?.[column];
+ const errorType = extractFormulaError(cell, !!arrayFormulaCellData);
+
+ // Check if the cell value is an error
+ if (errorType) {
+ errors.push({
+ sheetName,
+ row,
+ column,
+ formula: cell.f || '',
+ errorType,
+ });
+ }
+ });
+ });
+
+ return errors;
+ }
+}
+
+FWorkbook.extend(FWorkbookEngineFormulaMixin);
+declare module '@univerjs/sheets/facade' {
+ // eslint-disable-next-line ts/naming-convention
+ interface FWorkbook extends IFWorkbookEngineFormulaMixin { }
+}
diff --git a/packages/sheets-formula/src/facade/index.ts b/packages/sheets-formula/src/facade/index.ts
index f291782684..3858ad6e0b 100644
--- a/packages/sheets-formula/src/facade/index.ts
+++ b/packages/sheets-formula/src/facade/index.ts
@@ -17,6 +17,8 @@
import './f-univer';
import './f-formula';
import './f-enum';
+import './f-workbook';
+import './f-range';
export type * from './f-formula';
export type * from './f-univer';
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 32475aff4f..23ebdb5395 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2421,6 +2421,9 @@ importers:
'@univerjs/engine-formula':
specifier: workspace:*
version: link:../engine-formula
+ '@univerjs/engine-render':
+ specifier: workspace:*
+ version: link:../engine-render
'@univerjs/rpc':
specifier: workspace:*
version: link:../rpc