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.

docs: add getFormulas (#2119)

Dushusir576e9a3634d1
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..1dc7eb42d5 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,27 @@ describe('Test formula data model', () => {
expect(formulaData).toStrictEqual(result);
});
});
+
+ describe('getFormulaStringByCell', () => {
+ it('get formula string by cell', () => {
+ formulaDataModel.initFormulaData();
+
+ const unitId = 'test';
+ const sheetId = 'sheet1';
+
+ const result = [
+ ['=SUM(A1)'],
+ ['=SUM(A2)'],
+ ['=SUM(A3)'],
+ ['=SUM(A4)'],
+ ];
+
+ for (let i = 0; i < 4; i++) {
+ const formulaString = formulaDataModel.getFormulaStringByCell(i, 3, sheetId, unitId);
+ expect(formulaString).toBe(result[i][0]);
+ }
+ });
+ });
});
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 f5a51f21c4..7c52a7dc2f 100644
--- a/packages/engine-formula/src/models/formula-data.model.ts
+++ b/packages/engine-formula/src/models/formula-data.model.ts
@@ -499,6 +499,50 @@ export class FormulaDataModel extends Disposable {
return formulaIdMap;
}
+
+ getFormulaStringByCell(row: number, column: number, sheetId: string, unitId: string) {
+ const formulaDataItem = this.getFormulaDataItem(row, column, sheetId, unitId);
+
+ if (formulaDataItem == null) {
+ return null;
+ }
+
+ const { f, si, x = 0, y = 0 } = formulaDataItem;
+
+ // x and y support negative numbers. Negative numbers appear when the drop-down fill moves up or to the left.
+ if (si != null && (x !== 0 || y !== 0)) {
+ let formulaString = '';
+ if (f.length > 0) {
+ formulaString = f;
+ } else {
+ const originItem = this.getFormulaItemBySId(
+ si,
+ sheetId,
+ unitId
+ );
+
+ if (originItem == null || originItem.f.length === 0) {
+ return null;
+ }
+
+ formulaString = originItem.f;
+ }
+
+ formulaString = this._lexerTreeBuilder.moveFormulaRefOffset(
+ formulaString,
+ x,
+ y
+ );
+
+ return formulaString;
+ }
+
+ if (isFormulaString(f)) {
+ return f;
+ }
+
+ return null;
+ }
}
export function initSheetFormulaData(
diff --git a/packages/facade/src/apis/__tests__/create-test-bed.ts b/packages/facade/src/apis/__tests__/create-test-bed.ts
index d3421fc690..b94963afd3 100644
--- a/packages/facade/src/apis/__tests__/create-test-bed.ts
+++ b/packages/facade/src/apis/__tests__/create-test-bed.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IWorkbookData, Workbook } from '@univerjs/core';
+import type { IWorkbookData, UnitModel, Workbook } from '@univerjs/core';
import {
ILogService,
IUniverInstanceService,
@@ -26,7 +26,7 @@ import {
Univer,
UniverInstanceType,
} from '@univerjs/core';
-import { FunctionService, IFunctionService } from '@univerjs/engine-formula';
+import { FormulaDataModel, FunctionService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';
import { ISocketService, WebSocketService } from '@univerjs/network';
import { SelectionManagerService, SheetInterceptorService, SheetPermissionService } from '@univerjs/sheets';
import {
@@ -56,7 +56,30 @@ function getTestWorkbookDataDemo(): IWorkbookData {
sheet1: {
id: 'sheet1',
name: 'sheet1',
- cellData: {},
+ cellData: {
+ 0: {
+ 3: {
+ f: '=SUM(A1)',
+ si: '3e4r5t',
+ },
+ },
+ 1: {
+ 3: {
+ f: '=SUM(A2)',
+ si: 'OSPtzm',
+ },
+ },
+ 2: {
+ 3: {
+ si: 'OSPtzm',
+ },
+ },
+ 3: {
+ 3: {
+ si: 'OSPtzm',
+ },
+ },
+ },
rowCount: 100,
columnCount: 100,
},
@@ -77,7 +100,7 @@ function getTestWorkbookDataDemo(): IWorkbookData {
export interface ITestBed {
univer: Univer;
get: Injector['get'];
- sheet: Workbook;
+ sheet: UnitModel<Workbook>;
univerAPI: FUniver;
}
@@ -117,6 +140,8 @@ export function createTestBed(workbookData?: IWorkbookData, dependencies?: Depen
injector.add([IShortcutService, { useClass: DesktopShortcutService }]);
injector.add([IPlatformService, { useClass: DesktopPlatformService }]);
injector.add([SheetSkeletonManagerService]);
+ injector.add([FormulaDataModel]);
+ injector.add([LexerTreeBuilder]);
SheetsConditionalFormattingPlugin.dependencyList.forEach((d) => {
injector.add(d);
});
@@ -132,7 +157,7 @@ export function createTestBed(workbookData?: IWorkbookData, dependencies?: Depen
});
univer.registerPlugin(TestPlugin);
- const sheet = univer.createUniverSheet(workbookData || getTestWorkbookDataDemo());
+ const sheet = univer.createUnit(UniverInstanceType.UNIVER_SHEET, workbookData || getTestWorkbookDataDemo());
const univerInstanceService = injector.get(IUniverInstanceService);
univerInstanceService.focusUnit('test');
diff --git a/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts
index b84ab7c3a2..4cb107062e 100644
--- a/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts
+++ b/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts
@@ -20,6 +20,7 @@ import { SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetRangeValuesMut
import type { Injector } from '@wendellhu/redi';
import { beforeEach, describe, expect, it } from 'vitest';
+import { FormulaDataModel } from '@univerjs/engine-formula';
import type { FUniver } from '../../facade';
import { createTestBed } from '../../__tests__/create-test-bed';
@@ -194,6 +195,21 @@ describe('Test FRange', () => {
expect(range?.getCellStyleData()?.bl).toBe(1);
});
+ it('Range getFormulas', () => {
+ const formulaDataModel = get(FormulaDataModel);
+ formulaDataModel.initFormulaData();
+
+ const activeSheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
+ const formulas = activeSheet?.getRange(0, 3, 5, 1)?.getFormulas();
+ expect(formulas).toStrictEqual([
+ ['=SUM(A1)'],
+ ['=SUM(A2)'],
+ ['=SUM(A3)'],
+ ['=SUM(A4)'],
+ [''],
+ ]);
+ });
+
it('Range setFontWeight', () => {
const activeSheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
diff --git a/packages/facade/src/apis/sheets/f-range.ts b/packages/facade/src/apis/sheets/f-range.ts
index 5ccde1d6ee..8b18617089 100644
--- a/packages/facade/src/apis/sheets/f-range.ts
+++ b/packages/facade/src/apis/sheets/f-range.ts
@@ -42,8 +42,9 @@ import {
} from '@univerjs/sheets';
import type { ISetNumfmtCommandParams } from '@univerjs/sheets-numfmt';
import { SetNumfmtCommand } from '@univerjs/sheets-numfmt';
-import { Inject, Injector } from '@wendellhu/redi';
+import { FormulaDataModel } from '@univerjs/engine-formula';
+import { Inject } from '@wendellhu/redi';
import type { FHorizontalAlignment, FVerticalAlignment } from './utils';
import {
covertCellValue,
@@ -63,8 +64,8 @@ export class FRange {
private readonly _workbook: Workbook,
private readonly _worksheet: Worksheet,
private readonly _range: IRange,
- @Inject(Injector) private readonly _injector: Injector,
- @ICommandService private readonly _commandService: ICommandService
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel
) { }
getRow(): number {
@@ -109,6 +110,31 @@ export class FRange {
return this._worksheet.getCell(this._range.startRow, this._range.startColumn)?.v ?? null;
}
+ /**
+ * Returns the formulas (A1 notation) for the cells in the range. Entries in the 2D array are empty strings for cells with no formula.
+ * @returns A two-dimensional array of formulas in string format.
+ */
+ getFormulas(): string[][] {
+ const formulas: string[][] = [];
+
+ const { startRow, endRow, startColumn, endColumn } = this._range;
+ const sheetId = this._worksheet.getSheetId();
+ const unitId = this._workbook.getUnitId();
+
+ for (let row = startRow; row <= endRow; row++) {
+ const rowFormulas: string[] = [];
+
+ for (let col = startColumn; col <= endColumn; col++) {
+ const formulaString = this._formulaDataModel.getFormulaStringByCell(row, col, sheetId, unitId);
+ rowFormulas.push(formulaString || '');
+ }
+
+ formulas.push(rowFormulas);
+ }
+
+ return formulas;
+ }
+
getWrap(): boolean {
return this._worksheet.getRange(this._range).getWrap() === BooleanNumber.TRUE;
}
diff --git a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
index 4be2f6433e..3388940d4c 100644
--- a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
@@ -86,43 +86,10 @@ export class FormulaEditorShowController extends Disposable {
let cellInfo: Nullable<ICellDataForSheetInterceptor> = null;
- const formulaDataItem = this._formulaDataModel.getFormulaDataItem(
- row,
- col,
- subUnitId,
- unitId
- );
-
- if (formulaDataItem != null) {
- const { f, si, x = 0, y = 0 } = formulaDataItem;
-
- // x and y support negative numbers. Negative numbers appear when the drop-down fill moves up or to the left.
- if (si != null && (x !== 0 || y !== 0)) {
- let formulaString = '';
- if (f.length > 0) {
- formulaString = f;
- } else {
- const originItem = this._formulaDataModel.getFormulaItemBySId(
- si,
- subUnitId,
- unitId
- );
-
- if (originItem == null || originItem.f.length === 0) {
- return next(value);
- }
+ const formulaString = this._formulaDataModel.getFormulaStringByCell(row, col, subUnitId, unitId);
- formulaString = originItem.f;
- }
-
- const newFormulaString = this._lexerTreeBuilder.moveFormulaRefOffset(
- formulaString,
- x,
- y
- );
-
- cellInfo = { f: newFormulaString };
- }
+ if (formulaString !== null) {
+ cellInfo = { f: formulaString };
}
/**