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(facade): supplement f-workbook f-worksheet f-range facade (#4733)

wpxp123456edddb71ef6cd
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 9acca32ca8..704f358781 100644
--- a/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts
+++ b/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts
@@ -18,7 +18,7 @@
import type { ICellData, Injector, IRange, IStyleData, Nullable } from '@univerjs/core';
import type { FUniver } from '../../everything';
-import { DataValidationType, HorizontalAlign, ICommandService, IUniverInstanceService, VerticalAlign, WrapStrategy } from '@univerjs/core';
+import { DataValidationType, HorizontalAlign, ICommandService, IUniverInstanceService, LifecycleStages, VerticalAlign, WrapStrategy } from '@univerjs/core';
import { AddWorksheetMergeCommand, SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand } from '@univerjs/sheets';
import { AddSheetDataValidationCommand } from '@univerjs/sheets-data-validation';
import { ClearSheetsFilterCriteriaCommand, RemoveSheetFilterCommand, SetSheetFilterRangeCommand, SetSheetsFilterCriteriaCommand } from '@univerjs/sheets-filter';
@@ -819,4 +819,79 @@ describe('Test FRange', () => {
expect(range.getValue()).toBe('1,234.5678');
});
});
+
+ it('Range getRawValue and getDisplayValue', () => {
+ univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, ({ stage }) => {
+ if (stage === LifecycleStages.Steady) {
+ const fWorkbook = univerAPI.getActiveWorkbook()!;
+ const fWorksheet = fWorkbook.getActiveSheet();
+ const fRange = fWorksheet.getRange('A1:B2');
+
+ fRange.setValueForCell({
+ v: 0.2,
+ s: {
+ n: {
+ pattern: '0%',
+ },
+ },
+ });
+
+ expect(fRange.getRawValue()).toEqual(0.2);
+ expect(fRange.getDisplayValue()).toEqual('20%');
+ }
+ });
+ });
+
+ it('Range getRawValues and getDisplayValues', () => {
+ univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, ({ stage }) => {
+ if (stage === LifecycleStages.Steady) {
+ const fWorkbook = univerAPI.getActiveWorkbook()!;
+ const fWorksheet = fWorkbook.getActiveSheet();
+ const fRange = fWorksheet.getRange('A1:B2');
+
+ fRange.setValues([
+ [
+ {
+ v: 0.2,
+ s: {
+ n: {
+ pattern: '0%',
+ },
+ },
+ },
+ {
+ v: 45658,
+ s: {
+ n: {
+ pattern: 'yyyy-mm-dd',
+ },
+ },
+ },
+ ],
+ [
+ {
+ v: 1234.567,
+ s: {
+ n: {
+ pattern: '#,##0.00',
+ },
+ },
+ },
+ {
+ v: null,
+ },
+ ],
+ ]);
+
+ expect(fRange.getRawValues()).toEqual([
+ [0.2, 45658],
+ [1234.567, null],
+ ]);
+ expect(fRange.getDisplayValues()).toEqual([
+ ['20%', '2025-01-01'],
+ ['1,234.57', ''],
+ ]);
+ }
+ });
+ });
});
diff --git a/packages/sheets-numfmt/src/facade/f-range.ts b/packages/sheets-numfmt/src/facade/f-range.ts
index 6f7564b61d..365cf81c1e 100644
--- a/packages/sheets-numfmt/src/facade/f-range.ts
+++ b/packages/sheets-numfmt/src/facade/f-range.ts
@@ -34,10 +34,57 @@ export interface IFRangeSheetsNumfmtMixin {
* const fWorksheet = fWorkbook.getActiveSheet();
* const fRange = fWorksheet.getRange('A1');
* fRange.setValue(1234.567).setNumberFormat('#,##0.00');
- * console.log(fRange.getValue()); // 1,234.57
+ * console.log(fRange.getDisplayValue()); // 1,234.57
* ```
*/
setNumberFormat(pattern: string): FRange;
+
+ /**
+ * Sets a rectangular grid of number formats (must match dimensions of this range).
+ * @param {string[][]} patterns - A two-dimensional array of number formats.
+ * @returns {FRange} The FRange instance for chaining.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * fRange.setValues([
+ * [1234.567, 0.1234],
+ * [45658, 0.9876]
+ * ]).setNumberFormats([
+ * ['#,##0.00', '0.00%'],
+ * ['yyyy-MM-DD', '']
+ * ]);
+ * console.log(fRange.getDisplayValues()); // [['1,234.57', '12.34%'], ['2025-01-01', 0.9876]]
+ * ```
+ */
+ setNumberFormats(patterns: string[][]): FRange;
+
+ /**
+ * Get the number formatting of the top-left cell of the given range. Empty cells return an empty string.
+ * @returns {string} The number format of the top-left cell of the range.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * console.log(fRange.getNumberFormat());
+ * ```
+ */
+ getNumberFormat(): string;
+
+ /**
+ * Returns the number formats for the cells in the range.
+ * @returns {string[][]} A two-dimensional array of number formats.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * console.log(fRange.getNumberFormats());
+ * ```
+ */
+ getNumberFormats(): string[][];
}
export class FRangeLegacy extends FRange implements IFRangeSheetsNumfmtMixin {
@@ -55,6 +102,33 @@ export class FRangeLegacy extends FRange implements IFRangeSheetsNumfmtMixin {
return this;
}
+
+ override setNumberFormats(patterns: string[][]): FRange {
+ const values: ISetNumfmtCommandParams['values'] = [];
+
+ // Add number format info to the `values` array.
+ this.forEach((row, col) => {
+ const pattern = patterns[row]?.[col];
+ values.push({ row, col, pattern });
+ });
+ this._commandService.syncExecuteCommand(SetNumfmtCommand.id, {
+ unitId: this._workbook.getUnitId(),
+ subUnitId: this._worksheet.getSheetId(),
+ values,
+ } as ISetNumfmtCommandParams);
+
+ return this;
+ }
+
+ override getNumberFormat(): string {
+ const style = this.getCellStyle();
+ return style?.numberFormat?.pattern ?? '';
+ }
+
+ override getNumberFormats(): string[][] {
+ const styles = this.getCellStyles();
+ return styles.map((row) => row.map((cellStyle) => cellStyle?.numberFormat?.pattern ?? ''));
+ }
}
FRange.extend(FRangeLegacy);
diff --git a/packages/sheets-ui/src/facade/f-worksheet.ts b/packages/sheets-ui/src/facade/f-worksheet.ts
index 3a14002329..3bc5c1b648 100644
--- a/packages/sheets-ui/src/facade/f-worksheet.ts
+++ b/packages/sheets-ui/src/facade/f-worksheet.ts
@@ -18,8 +18,9 @@ import type { IDisposable, IRange, Nullable } from '@univerjs/core';
import type { IColumnsHeaderCfgParam, IRowsHeaderCfgParam, RenderComponentType, RenderManagerService, SpreadsheetColumnHeader, SpreadsheetRowHeader, SpreadsheetSkeleton } from '@univerjs/engine-render';
import type { IScrollState, IViewportScrollState } from '@univerjs/sheets-ui';
-import { ICommandService, toDisposable } from '@univerjs/core';
+import { BooleanNumber, ICommandService, toDisposable } from '@univerjs/core';
import { IRenderManagerService, SHEET_VIEWPORT_KEY, sheetContentViewportKeys } from '@univerjs/engine-render';
+import { SetWorksheetRowIsAutoHeightMutation } from '@univerjs/sheets';
import { SetColumnHeaderHeightCommand, SetRowHeaderWidthCommand, SetWorksheetColAutoWidthCommand, SetZoomRatioCommand, SHEET_VIEW_KEY, SheetScrollManagerService, SheetSkeletonManagerService, SheetsScrollRenderController } from '@univerjs/sheets-ui';
import { FWorksheet } from '@univerjs/sheets/facade';
@@ -139,21 +140,65 @@ export interface IFWorksheetSkeletonMixin {
getSkeleton(): Nullable<SpreadsheetSkeleton>;
/**
- * Set the column width to auto width.
- * @param {number} columnPosition - Column position index
- * @param {number} numColumn - Number of columns
+ * Sets the width of the given column to fit its contents.
+ * @param {number} columnPosition - The position of the given column to resize. index starts at 0.
* @returns {FWorksheet} - The FWorksheet instance for chaining.
* @example
* ```ts
* const fWorkbook = univerAPI.getActiveWorkbook();
* const fWorksheet = fWorkbook.getActiveSheet();
*
- * // Set A:C columns to auto width
- * fWorksheet.setColumnAutoWidth(0, 3);
+ * // Set the long text value in cell A1
+ * const fRange = fWorksheet.getRange('A1');
+ * fRange.setValue('Whenever it is a damp, drizzly November in my soul...');
+ *
+ * // Set the column A to a width which fits the text
+ * fWorksheet.autoResizeColumn(0);
+ * ```
+ */
+ autoResizeColumn(columnPosition: number): FWorksheet;
+
+ /**
+ * Sets the width of all columns starting at the given column position to fit their contents.
+ * @param {number} startColumn - The position of the first column to resize. index starts at 0.
+ * @param {number} numColumns - The number of columns to auto-resize.
+ * @returns {FWorksheet} - The FWorksheet instance for chaining.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ *
+ * // Set the A:C columns to a width that fits their text.
+ * fWorksheet.autoResizeColumns(0, 3);
* ```
*/
+ autoResizeColumns(startColumn: number, numColumns: number): FWorksheet;
+
+ /**
+ * Sets the width of all columns starting at the given column position to fit their contents.
+ * @deprecated use `autoResizeColumns` instead
+ * @param {number} columnPosition - The position of the first column to resize. index starts at 0.
+ * @param {number} numColumn - The number of columns to auto-resize.
+ * @returns {FWorksheet} - The FWorksheet instance for chaining.
+ */
setColumnAutoWidth(columnPosition: number, numColumn: number): FWorksheet;
+ /**
+ * Sets the height of all rows starting at the given row position to fit their contents.
+ * @param {number} startRow - The position of the first row to resize. index starts at 0.
+ * @param {number} numRows - The number of rows to auto-resize.
+ * @returns {FWorksheet} - The FWorksheet instance for chaining.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ *
+ * // Set the first 3 rows to a height that fits their text.
+ * fWorksheet.autoResizeRows(0, 3);
+ * ```
+ */
+ autoResizeRows(startRow: number, numRows: number): FWorksheet;
+
/**
* Customize the column header of the spreadsheet.
* @param {IColumnsHeaderCfgParam} cfg The configuration of the column header.
@@ -351,13 +396,17 @@ export class FWorksheetSkeletonMixin extends FWorksheet implements IFWorksheetSk
return service?.getWorksheetSkeleton(this._worksheet.getSheetId())?.skeleton;
}
- override setColumnAutoWidth(columnPosition: number, numColumn: number): FWorksheet {
+ override autoResizeColumn(columnPosition: number): FWorksheet {
+ return this.autoResizeColumns(columnPosition, 1);
+ }
+
+ override autoResizeColumns(startColumn: number, numColumns: number): FWorksheet {
const unitId = this._workbook.getUnitId();
const subUnitId = this._worksheet.getSheetId();
const ranges = [
{
- startColumn: columnPosition,
- endColumn: columnPosition + numColumn - 1,
+ startColumn,
+ endColumn: startColumn + numColumns - 1,
startRow: 0,
endRow: this._worksheet.getRowCount() - 1,
},
@@ -372,6 +421,32 @@ export class FWorksheetSkeletonMixin extends FWorksheet implements IFWorksheetSk
return this;
}
+ override setColumnAutoWidth(columnPosition: number, numColumn: number): FWorksheet {
+ return this.autoResizeColumns(columnPosition, numColumn);
+ }
+
+ override autoResizeRows(startRow: number, numRows: number): FWorksheet {
+ const unitId = this._workbook.getUnitId();
+ const subUnitId = this._worksheet.getSheetId();
+ const ranges = [
+ {
+ startRow,
+ endRow: startRow + numRows - 1,
+ startColumn: 0,
+ endColumn: this._worksheet.getColumnCount() - 1,
+ },
+ ];
+
+ this._commandService.syncExecuteCommand(SetWorksheetRowIsAutoHeightMutation.id, {
+ unitId,
+ subUnitId,
+ ranges,
+ autoHeightInfo: BooleanNumber.TRUE,
+ });
+
+ return this;
+ }
+
override customizeColumnHeader(cfg: IColumnsHeaderCfgParam): void {
const activeSheet = this;
const unitId = this._fWorkbook.getId();
diff --git a/packages/sheets/src/commands/commands/append-row.command.ts b/packages/sheets/src/commands/commands/append-row.command.ts
new file mode 100644
index 0000000000..234f9ed2e4
--- /dev/null
+++ b/packages/sheets/src/commands/commands/append-row.command.ts
@@ -0,0 +1,137 @@
+/**
+ * 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 { IAccessor, ICellData, ICommand, IMutationInfo, IObjectMatrixPrimitiveType } from '@univerjs/core';
+import type {
+ IInsertColMutationParams,
+ IInsertRowMutationParams,
+ IRemoveColMutationParams,
+ IRemoveRowsMutationParams,
+} from '../../basics/interfaces/mutation-interface';
+
+import type { ISetRangeValuesMutationParams } from '../mutations/set-range-values.mutation';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+ sequenceExecute,
+} from '@univerjs/core';
+import {
+ InsertColMutation,
+ InsertColMutationUndoFactory,
+ InsertRowMutation,
+ InsertRowMutationUndoFactory,
+} from '../mutations/insert-row-col.mutation';
+import { RemoveColMutation, RemoveRowMutation } from '../mutations/remove-row-col.mutation';
+import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../mutations/set-range-values.mutation';
+
+export interface IAppendRowCommandParams {
+ unitId: string;
+ subUnitId: string;
+ cellValue: IObjectMatrixPrimitiveType<ICellData>;
+ insertRowNums?: number;
+ insertColumnNums?: number;
+ maxRows?: number;
+ maxColumns?: number;
+}
+export const AppendRowCommandId = 'sheet.command.append-row';
+
+/**
+ * this command and its interface should not be exported from index.ts
+ *
+ * @internal
+ */
+export const AppendRowCommand: ICommand<IAppendRowCommandParams> = {
+ type: CommandType.COMMAND,
+ id: AppendRowCommandId,
+ handler: (accessor: IAccessor, params: IAppendRowCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const { unitId, subUnitId, cellValue, insertRowNums, insertColumnNums, maxRows, maxColumns } = params;
+
+ // Set row values
+ const setRangeValuesMutationRedoParams: ISetRangeValuesMutationParams = {
+ unitId,
+ subUnitId,
+ cellValue,
+ };
+ const setRangeValuesMutationUndoParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(
+ accessor,
+ setRangeValuesMutationRedoParams
+ );
+
+ const redoMutations: IMutationInfo[] = [{ id: SetRangeValuesMutation.id, params: setRangeValuesMutationRedoParams }];
+ const undoMutations: IMutationInfo[] = [{ id: SetRangeValuesMutation.id, params: setRangeValuesMutationUndoParams }];
+
+ // If the last row is not empty, insert a row in last
+ if (insertRowNums) {
+ // Insert a row in last
+ const insertRowRedoParams: IInsertRowMutationParams = {
+ unitId,
+ subUnitId,
+ range: {
+ startRow: maxRows as number,
+ endRow: maxRows as number,
+ startColumn: 0,
+ endColumn: (maxColumns as number) - 1,
+ },
+ };
+ const insertRowUndoParams: IRemoveRowsMutationParams = InsertRowMutationUndoFactory(
+ accessor,
+ insertRowRedoParams
+ );
+
+ redoMutations.unshift({ id: InsertRowMutation.id, params: insertRowRedoParams });
+ undoMutations.push({ id: RemoveRowMutation.id, params: insertRowUndoParams });
+ }
+
+ // If the append row data has more columns than the current sheet, insert columns in last
+ if (insertColumnNums) {
+ // Insert columns in last
+ const insertColRedoParams: IInsertColMutationParams = {
+ unitId,
+ subUnitId,
+ range: {
+ startRow: 0,
+ endRow: (maxRows as number) - 1,
+ startColumn: maxColumns as number,
+ endColumn: (maxColumns as number) - 1 + insertColumnNums,
+ },
+ };
+ const insertColUndoParams: IRemoveColMutationParams = InsertColMutationUndoFactory(
+ accessor,
+ insertColRedoParams
+ );
+
+ redoMutations.unshift({ id: InsertColMutation.id, params: insertColRedoParams });
+ undoMutations.push({ id: RemoveColMutation.id, params: insertColUndoParams });
+ }
+
+ const result = sequenceExecute(redoMutations, commandService);
+
+ if (result.result) {
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations,
+ redoMutations,
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/sheets/src/commands/commands/set-style.command.ts b/packages/sheets/src/commands/commands/set-style.command.ts
index c873b31236..d450e01a10 100644
--- a/packages/sheets/src/commands/commands/set-style.command.ts
+++ b/packages/sheets/src/commands/commands/set-style.command.ts
@@ -528,7 +528,7 @@ export const SetTextWrapCommand: ICommand<ISetTextWrapCommandParams> = {
},
};
-export interface ISetTextRotationCommandParams {
+export interface ISetTextRotationCommandParams extends ISetStyleCommonParams {
value: number | string;
}
@@ -544,6 +544,9 @@ export const SetTextRotationCommand: ICommand<ISetTextRotationCommandParams> = {
const commandService = accessor.get(ICommandService);
const setStyleParams: ISetStyleCommandParams<ITextRotation> = {
+ unitId: params.unitId,
+ subUnitId: params.subUnitId,
+ range: params.range,
style: {
type: 'tr',
value,
diff --git a/packages/sheets/src/controllers/basic-worksheet.controller.ts b/packages/sheets/src/controllers/basic-worksheet.controller.ts
index 99fc59b175..d974cb2e7f 100644
--- a/packages/sheets/src/controllers/basic-worksheet.controller.ts
+++ b/packages/sheets/src/controllers/basic-worksheet.controller.ts
@@ -21,6 +21,7 @@ import { DataSyncPrimaryController } from '@univerjs/rpc';
import { AddRangeProtectionCommand } from '../commands/commands/add-range-protection.command';
import { AddWorksheetProtectionCommand } from '../commands/commands/add-worksheet-protection.command';
import { SetWorksheetRangeThemeStyleCommand } from '../commands/commands/add-worksheet-range-theme.command';
+import { AppendRowCommand } from '../commands/commands/append-row.command';
import { ClearSelectionAllCommand } from '../commands/commands/clear-selection-all.command';
import { ClearSelectionContentCommand } from '../commands/commands/clear-selection-content.command';
import { ClearSelectionFormatCommand } from '../commands/commands/clear-selection-format.command';
@@ -205,6 +206,7 @@ export class BasicWorksheetController extends Disposable implements IDisposable
const onlyRegisterFormulaRelatedMutations = this._configService.getConfig(ONLY_REGISTER_FORMULA_RELATED_MUTATIONS_KEY) ?? false;
if (!onlyRegisterFormulaRelatedMutations) {
[
+ AppendRowCommand,
ClearSelectionAllCommand,
ClearSelectionContentCommand,
ClearSelectionFormatCommand,
diff --git a/packages/sheets/src/facade/f-range.ts b/packages/sheets/src/facade/f-range.ts
index adb87d2ade..1115685703 100644
--- a/packages/sheets/src/facade/f-range.ts
+++ b/packages/sheets/src/facade/f-range.ts
@@ -15,12 +15,13 @@
*/
import type { BorderStyleTypes, BorderType, CellValue, CustomData, ICellData, IColorStyle, IDocumentData, IObjectMatrixPrimitiveType, IRange, IStyleData, ITextDecoration, Nullable, Workbook, Worksheet } from '@univerjs/core';
-import type { ISetBorderBasicCommandParams, ISetHorizontalTextAlignCommandParams, ISetRangeValuesCommandParams, ISetStyleCommandParams, ISetTextWrapCommandParams, ISetVerticalTextAlignCommandParams, IStyleTypeValue, SplitDelimiterEnum } from '@univerjs/sheets';
+import type { ISetBorderBasicCommandParams, ISetHorizontalTextAlignCommandParams, ISetRangeValuesCommandParams, ISetSelectionsOperationParams, ISetStyleCommandParams, ISetTextRotationCommandParams, ISetTextWrapCommandParams, ISetVerticalTextAlignCommandParams, IStyleTypeValue, SplitDelimiterEnum } from '@univerjs/sheets';
+import type { IFacadeClearOptions } from './f-worksheet';
import type { FHorizontalAlignment, FVerticalAlignment } from './utils';
-import { BooleanNumber, Dimension, ICommandService, Inject, Injector, Rectangle, RichTextValue, TextStyleValue, WrapStrategy } from '@univerjs/core';
+import { BooleanNumber, DEFAULT_STYLES, Dimension, ICommandService, Inject, Injector, isNullCell, Rectangle, RichTextValue, TextStyleValue, WrapStrategy } from '@univerjs/core';
import { FBaseInitialable } from '@univerjs/core/facade';
import { FormulaDataModel, serializeRange, serializeRangeWithSheet } from '@univerjs/engine-formula';
-import { addMergeCellsUtil, DeleteWorksheetRangeThemeStyleCommand, getAddMergeMutationRangeByType, RemoveWorksheetMergeCommand, SetBorderBasicCommand, SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand, SetWorksheetRangeThemeStyleCommand, SheetRangeThemeService, SplitTextToColumnsCommand } from '@univerjs/sheets';
+import { addMergeCellsUtil, ClearSelectionAllCommand, ClearSelectionContentCommand, ClearSelectionFormatCommand, DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, DeleteWorksheetRangeThemeStyleCommand, getAddMergeMutationRangeByType, getPrimaryForRange, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, RemoveWorksheetMergeCommand, SetBorderBasicCommand, SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetSelectionsOperation, SetStyleCommand, SetTextRotationCommand, SetTextWrapCommand, SetVerticalTextAlignCommand, SetWorksheetRangeThemeStyleCommand, SheetRangeThemeService, SplitTextToColumnsCommand } from '@univerjs/sheets';
import { FWorkbook } from './f-workbook';
import { covertCellValue, covertCellValues, transformCoreHorizontalAlignment, transformCoreVerticalAlignment, transformFacadeHorizontalAlignment, transformFacadeVerticalAlignment } from './utils';
@@ -109,14 +110,14 @@ export class FRange extends FBaseInitialable {
}
/**
- * Gets the starting row number of the applied area
- * @returns {number} The starting row number of the area
+ * Gets the starting row index of the range. index starts at 0.
+ * @returns {number} The starting row index of the range.
* @example
* ```ts
* const fWorkbook = univerAPI.getActiveWorkbook();
* const fWorksheet = fWorkbook.getActiveSheet();
* const fRange = fWorksheet.getRange('A1:B2');
- * console.log(fRange.getRow());
+ * console.log(fRange.getRow()); // 0
* ```
*/
getRow(): number {
@@ -124,20 +125,50 @@ export class FRange extends FBaseInitialable {
}
/**
- * Gets the starting column number of the applied area
- * @returns {number} The starting column number of the area
+ * Gets the ending row index of the range. index starts at 0.
+ * @returns {number} The ending row index of the range.
* @example
* ```ts
* const fWorkbook = univerAPI.getActiveWorkbook();
* const fWorksheet = fWorkbook.getActiveSheet();
* const fRange = fWorksheet.getRange('A1:B2');
- * console.log(fRange.getColumn());
+ * console.log(fRange.getLastRow()); // 1
+ * ```
+ */
+ getLastRow(): number {
+ return this._range.endRow;
+ }
+
+ /**
+ * Gets the starting column index of the range. index starts at 0.
+ * @returns {number} The starting column index of the range.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * console.log(fRange.getColumn()); // 0
* ```
*/
getColumn(): number {
return this._range.startColumn;
}
+ /**
+ * Gets the ending column index of the range. index starts at 0.
+ * @returns {number} The ending column index of the range.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * console.log(fRange.getLastColumn()); // 1
+ * ```
+ */
+ getLastColumn(): number {
+ return this._range.endColumn;
+ }
+
/**
* Gets the width of the applied area
* @returns {number} The width of the area
@@ -262,7 +293,6 @@ export class FRange extends FBaseInitialable {
* ```
*/
getValue(): CellValue | null;
-
/**
* Return first cell value in this range
* @param {boolean} includeRichText Should the returns of this func to include rich text
@@ -291,6 +321,58 @@ export class FRange extends FBaseInitialable {
return this._worksheet.getCell(this._range.startRow, this._range.startColumn)?.v ?? null;
}
+ /**
+ * Returns the raw value of the top-left cell in the range. Empty cells return `null`.
+ * @returns {Nullable<CellValue>} The raw value of the cell. Returns `null` if the cell is empty.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * fRange.setValueForCell({
+ * v: 0.2,
+ * s: {
+ * n: {
+ * pattern: '0%',
+ * },
+ * },
+ * });
+ * console.log(fRange.getRawValue()); // 0.2
+ * ```
+ */
+ getRawValue(): Nullable<CellValue> {
+ const cell = this._worksheet.getCellMatrix().getValue(this._range.startRow, this._range.startColumn);
+ if (cell?.p && cell.p.body?.dataStream) return cell.p.body.dataStream;
+ if (cell?.v) return cell.v;
+ return null;
+ }
+
+ /**
+ * Returns the displayed value of the top-left cell in the range. The value is a String. Empty cells return an empty string.
+ * @returns {string} The displayed value of the cell. Returns an empty string if the cell is empty.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * fRange.setValueForCell({
+ * v: 0.2,
+ * s: {
+ * n: {
+ * pattern: '0%',
+ * },
+ * },
+ * });
+ * console.log(fRange.getDisplayValue()); // 20%
+ * ```
+ */
+ getDisplayValue(): string {
+ const cell = this._worksheet.getCell(this._range.startRow, this._range.startColumn);
+ if (cell?.p && cell.p.body?.dataStream) return cell.p.body.dataStream;
+ if (cell?.v) return String(cell.v);
+ return '';
+ }
+
/**
* Returns the cell values for the cells in the range.
* @returns {Nullable<CellValue>[][]} A two-dimensional array of cell values.
@@ -304,7 +386,6 @@ export class FRange extends FBaseInitialable {
* ```
*/
getValues(): Nullable<CellValue>[][];
-
/**
* Returns the cell values for the cells in the range.
* @param {boolean} includeRichText Should the returns of this func to include rich text
@@ -339,6 +420,140 @@ export class FRange extends FBaseInitialable {
return range;
}
+ /**
+ * Returns a two-dimensional array of the range raw values. Empty cells return `null`.
+ * @returns {Array<Array<Nullable<CellValue>>>} The raw value of the cell. Returns `null` if the cell is empty.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * fRange.setValues([
+ * [
+ * {
+ * v: 0.2,
+ * s: {
+ * n: {
+ * pattern: '0%',
+ * },
+ * },
+ * },
+ * {
+ * v: 45658,
+ * s: {
+ * n: {
+ * pattern: 'yyyy-mm-dd',
+ * },
+ * },
+ * }
+ * ],
+ * [
+ * {
+ * v: 1234.567,
+ * s: {
+ * n: {
+ * pattern: '#,##0.00',
+ * }
+ * }
+ * },
+ * null,
+ * ],
+ * ]);
+ * console.log(fRange.getRawValues()); // [[0.2, 45658], [1234.567, null]]
+ * ```
+ */
+ getRawValues(): Array<Array<Nullable<CellValue>>> {
+ const cellMatrix = this._worksheet.getCellMatrix();
+ const { startRow, endRow, startColumn, endColumn } = this._range;
+ const values: Array<Array<Nullable<CellValue>>> = [];
+
+ for (let r = startRow; r <= endRow; r++) {
+ const row: Array<Nullable<CellValue>> = [];
+
+ for (let c = startColumn; c <= endColumn; c++) {
+ const cell = cellMatrix.getValue(r, c);
+ if (cell?.p && cell.p.body?.dataStream) {
+ row.push(cell.p.body.dataStream);
+ } else if (cell?.v) {
+ row.push(cell.v);
+ } else {
+ row.push(null);
+ }
+ }
+
+ values.push(row);
+ }
+
+ return values;
+ }
+
+ /**
+ * Returns a two-dimensional array of the range displayed values. Empty cells return an empty string.
+ * @returns {string[][]} A two-dimensional array of values.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * fRange.setValues([
+ * [
+ * {
+ * v: 0.2,
+ * s: {
+ * n: {
+ * pattern: '0%',
+ * },
+ * },
+ * },
+ * {
+ * v: 45658,
+ * s: {
+ * n: {
+ * pattern: 'yyyy-mm-dd',
+ * },
+ * },
+ * }
+ * ],
+ * [
+ * {
+ * v: 1234.567,
+ * s: {
+ * n: {
+ * pattern: '#,##0.00',
+ * }
+ * }
+ * },
+ * null,
+ * ],
+ * ]);
+ * console.log(fRange.getDisplayValues()); // [['20%', '2025-01-01'], ['1,234.57', '']]
+ * ```
+ */
+ getDisplayValues(): string[][] {
+ const { startRow, endRow, startColumn, endColumn } = this._range;
+ const values: string[][] = [];
+
+ for (let r = startRow; r <= endRow; r++) {
+ const row: string[] = [];
+
+ for (let c = startColumn; c <= endColumn; c++) {
+ const cell = this._worksheet.getCell(r, c);
+
+ if (cell?.p && cell.p.body?.dataStream) {
+ row.push(cell.p.body.dataStream);
+ } else if (cell?.v) {
+ row.push(String(cell.v));
+ } else {
+ row.push('');
+ }
+ }
+
+ values.push(row);
+ }
+
+ return values;
+ }
+
/**
* Return first cell model data in this range
* @returns {ICellData | null} The cell model data
@@ -468,6 +683,26 @@ export class FRange extends FBaseInitialable {
return dataGrid.map((row) => row.map((data) => data?.p ? new RichTextValue(data.p) : data?.v));
}
+ /**
+ * Returns the formula (A1 notation) of the top-left cell in the range, or an empty string if the cell is empty or doesn't contain a formula.
+ * @returns {string} The formula for the cell.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * console.log(fRange.getFormula());
+ * ```
+ */
+ getFormula(): string {
+ return this._formulaDataModel.getFormulaStringByCell(
+ this._range.startRow,
+ this._range.startColumn,
+ this._worksheet.getSheetId(),
+ this._workbook.getUnitId()
+ ) ?? '';
+ }
+
/**
* 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 {string[][]} A two-dimensional array of formulas in string format.
@@ -501,8 +736,8 @@ export class FRange extends FBaseInitialable {
}
/**
- * Returns true if the cell wrap is enabled for the top left cell of the range.
- * @returns {boolean} True if the cell wrap is enabled
+ * Gets whether text wrapping is enabled for top-left cell in the range.
+ * @returns {boolean} whether text wrapping is enabled for the cell.
* @example
* ```ts
* const fWorkbook = univerAPI.getActiveWorkbook();
@@ -515,6 +750,22 @@ export class FRange extends FBaseInitialable {
return this._worksheet.getRange(this._range).getWrap() === BooleanNumber.TRUE;
}
+ /**
+ * Gets whether text wrapping is enabled for cells in the range.
+ * @returns {boolean[][]} A two-dimensional array of whether text wrapping is enabled for each cell in the range.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * console.log(fRange.getWraps());
+ */
+ getWraps(): boolean[][] {
+ const cells = this.getCellDatas();
+ const styles = this._workbook.getStyles();
+ return cells.map((row) => row.map((cell) => styles.getStyleByCell(cell)?.tb === WrapStrategy.WRAP));
+ }
+
/**
* Returns the text wrapping strategy for the top left cell of the range.
* @returns {WrapStrategy} The text wrapping strategy
@@ -531,8 +782,8 @@ export class FRange extends FBaseInitialable {
}
/**
- * Returns the horizontal alignment for the top left cell of the range.
- * @returns {string} The horizontal alignment
+ * Returns the horizontal alignment of the text (left/center/right) of the top-left cell in the range.
+ * @returns {string} The horizontal alignment of the text in the cell.
* @example
* ```ts
* const fWorkbook = univerAPI.getActiveWorkbook();
@@ -542,12 +793,29 @@ export class FRange extends FBaseInitialable {
* ```
*/
getHorizontalAlignment(): string {
- return transformCoreHorizontalAlignment(this._worksheet.getRange(this._range).getHorizontalAlignment());
+ const coreHorizontalAlignment = this._worksheet.getRange(this._range).getHorizontalAlignment();
+ return transformCoreHorizontalAlignment(coreHorizontalAlignment);
}
/**
- * Returns the vertical alignment for the top left cell of the range.
- * @returns {string} The vertical alignment
+ * Returns the horizontal alignments of the cells in the range.
+ * @returns {string[][]} A two-dimensional array of horizontal alignments of text associated with cells in the range.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * console.log(fRange.getHorizontalAlignments());
+ * ```
+ */
+ getHorizontalAlignments(): string[][] {
+ const coreHorizontalAlignments = this._worksheet.getRange(this._range).getHorizontalAlignments();
+ return coreHorizontalAlignments.map((row) => row.map((alignment) => transformCoreHorizontalAlignment(alignment)));
+ }
+
+ /**
+ * Returns the vertical alignment (top/middle/bottom) of the top-left cell in the range.
+ * @returns {string} The vertical alignment of the text in the cell.
* @example
* ```ts
* const fWorkbook = univerAPI.getActiveWorkbook();
@@ -560,6 +828,22 @@ export class FRange extends FBaseInitialable {
return transformCoreVerticalAlignment(this._worksheet.getRange(this._range).getVerticalAlignment());
}
+ /**
+ * Returns the vertical alignments of the cells in the range.
+ * @returns {string[][]} A two-dimensional array of vertical alignments of text associated with cells in the range.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * console.log(fRange.getVerticalAlignments());
+ * ```
+ */
+ getVerticalAlignments(): string[][] {
+ const coreVerticalAlignments = this._worksheet.getRange(this._range).getVerticalAlignments();
+ return coreVerticalAlignments.map((row) => row.map((alignment) => transformCoreVerticalAlignment(alignment)));
+ }
+
/**
* Set custom meta data for first cell in current range.
* @param {CustomData} data The custom meta data
@@ -659,6 +943,38 @@ export class FRange extends FBaseInitialable {
// #region editing
+ /**
+ * Returns the background color of the top-left cell in the range.
+ * @returns {string} The color code of the background.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * console.log(fRange.getBackground());
+ * ```
+ */
+ getBackground(): string {
+ const style = this.getCellStyle();
+ return style?.background?.rgb ?? DEFAULT_STYLES.bg.rgb;
+ }
+
+ /**
+ * Returns the background colors of the cells in the range.
+ * @returns {string[][]} A two-dimensional array of color codes of the backgrounds.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * console.log(fRange.getBackgrounds());
+ * ```
+ */
+ getBackgrounds(): string[][] {
+ const styles = this.getCellStyles();
+ return styles.map((row) => row.map((style) => style?.background?.rgb ?? DEFAULT_STYLES.bg.rgb));
+ }
+
/**
* Set background color for current range.
* @param {string} color The background color
@@ -703,6 +1019,28 @@ export class FRange extends FBaseInitialable {
return this;
}
+ /**
+ * Set rotation for text in current range.
+ * @param {number} rotation - The rotation angle in degrees
+ * @returns This range, for chaining
+ * @example
+ * ```typescript
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * fRange.setTextRotation(45);
+ * ```
+ */
+ setTextRotation(rotation: number): FRange {
+ this._commandService.syncExecuteCommand(SetTextRotationCommand.id, {
+ unitId: this._workbook.getUnitId(),
+ subUnitId: this._worksheet.getSheetId(),
+ range: this._range,
+ value: rotation,
+ } as ISetTextRotationCommandParams);
+ return this;
+ }
+
/**
* Sets the value of the range.
* @param {CellValue | ICellData} value The value can be a number, string, boolean, or standard cell format. If it begins with `=`, it is interpreted as a formula. The value is tiled to all cells in the range.
@@ -1408,11 +1746,26 @@ export class FRange extends FBaseInitialable {
* ```ts
* const fWorkbook = univerAPI.getActiveWorkbook();
* const fWorksheet = fWorkbook.getActiveSheet();
+ *
+ * // Set the range A1:B2 as the active range, default active cell is A1
* const fRange = fWorksheet.getRange('A1:B2');
* fRange.activate();
+ * console.log(fWorksheet.getActiveRange().getA1Notation()); // A1:B2
+ * console.log(fWorksheet.getActiveCell().getA1Notation()); // A1
+ *
+ * // Set the cell B2 as the active cell
+ * // Because B2 is in the active range A1:B2, the active range will not change, and the active cell will be changed to B2
* const cell = fWorksheet.getRange('B2');
- * cell.activateAsCurrentCell(); // the active cell will be B2
- * console.log(fWorksheet.getActiveRange().getA1Notation()); // B2
+ * cell.activateAsCurrentCell();
+ * console.log(fWorksheet.getActiveRange().getA1Notation()); // A1:B2
+ * console.log(fWorksheet.getActiveCell().getA1Notation()); // B2
+ *
+ * // Set the cell C3 as the active cell
+ * // Because C3 is not in the active range A1:B2, a new active range C3:C3 will be created, and the active cell will be changed to C3
+ * const cell2 = fWorksheet.getRange('C3');
+ * cell2.activateAsCurrentCell();
+ * console.log(fWorksheet.getActiveRange().getA1Notation()); // C3:C3
+ * console.log(fWorksheet.getActiveCell().getA1Notation()); // C3
* ```
*/
activateAsCurrentCell(): FRange {
@@ -1422,6 +1775,31 @@ export class FRange extends FBaseInitialable {
(!mergeInfo && this._range.startRow === this._range.endRow && this._range.startColumn === this._range.endColumn);
if (valid) {
+ const fWorkbook = this._injector.createInstance(FWorkbook, this._workbook);
+ const activeRange = fWorkbook.getActiveRange();
+
+ if (!activeRange || activeRange.getUnitId() !== this.getUnitId() || activeRange.getSheetId() !== this.getSheetId()) {
+ return this.activate();
+ }
+
+ if (Rectangle.contains(activeRange.getRange(), this._range)) {
+ const setSelectionOperationParams: ISetSelectionsOperationParams = {
+ unitId: this.getUnitId(),
+ subUnitId: this.getSheetId(),
+ selections: [
+ {
+ range: activeRange.getRange(),
+ primary: getPrimaryForRange(this.getRange(), this._worksheet),
+ style: null,
+ },
+ ],
+ };
+
+ this._commandService.syncExecuteCommand(SetSelectionsOperation.id, setSelectionOperationParams);
+
+ return this;
+ }
+
return this.activate();
} else {
throw new Error('The range is not a single cell');
@@ -1607,4 +1985,485 @@ export class FRange extends FBaseInitialable {
range: this._range,
});
}
+
+ /**
+ * Clears content and formatting information of the range. Or Optionally clears only the contents or only the formatting.
+ * @param {IFacadeClearOptions} [options] - Options for clearing the range. If not provided, the contents and formatting are cleared both.
+ * @param {boolean} [options.contentsOnly] - If true, the contents of the range are cleared. If false, the contents and formatting are cleared. Default is false.
+ * @param {boolean} [options.formatOnly] - If true, the formatting of the range is cleared. If false, the contents and formatting are cleared. Default is false.
+ * @returns {FWorksheet} Returns the current worksheet instance for method chaining
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorkSheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorkSheet.getRange('A1:D10');
+ *
+ * // clear the content and format of the range A1:D10
+ * fRange.clear();
+ *
+ * // clear the content only of the range A1:D10
+ * fRange.clear({ contentsOnly: true });
+ * ```
+ */
+ clear(options?: IFacadeClearOptions): FRange {
+ if (options && options.contentsOnly && !options.formatOnly) {
+ return this.clearContent();
+ }
+
+ if (options && options.formatOnly && !options.contentsOnly) {
+ return this.clearFormat();
+ }
+
+ this._commandService.syncExecuteCommand(ClearSelectionAllCommand.id, {
+ unitId: this._workbook.getUnitId(),
+ subUnitId: this._worksheet.getSheetId(),
+ ranges: [this._range],
+ options,
+ });
+ return this;
+ }
+
+ /**
+ * Clears content of the range, while preserving formatting information.
+ * @returns {FWorksheet} Returns the current worksheet instance for method chaining
+ * @example
+ * ```typescript
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorkSheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorkSheet.getRange('A1:D10');
+ *
+ * // clear the content only of the range A1:D10
+ * fRange.clearContent();
+ * ```
+ */
+ clearContent(): FRange {
+ this._commandService.syncExecuteCommand(ClearSelectionContentCommand.id, {
+ unitId: this._workbook.getUnitId(),
+ subUnitId: this._worksheet.getSheetId(),
+ ranges: [this._range],
+ });
+ return this;
+ }
+
+ /**
+ * Clears formatting information of the range, while preserving contents.
+ * @returns {FWorksheet} Returns the current worksheet instance for method chaining
+ * @example
+ * ```typescript
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorkSheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorkSheet.getRange('A1:D10');
+ * // clear the format only of the range A1:D10
+ * fRange.clearFormat();
+ * ```
+ */
+ clearFormat(): FRange {
+ this._commandService.syncExecuteCommand(ClearSelectionFormatCommand.id, {
+ unitId: this._workbook.getUnitId(),
+ subUnitId: this._worksheet.getSheetId(),
+ ranges: [this._range],
+ });
+ return this;
+ }
+
+ /**
+ * Inserts empty cells into this range. Existing data in the sheet along the provided dimension is shifted away from the inserted range.
+ * @param {Dimension} shiftDimension - The dimension along which to shift existing data.
+ * @example
+ * ```ts
+ * // Assume the active sheet empty sheet.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const values = [
+ * [1, 2, 3, 4],
+ * [2, 3, 4, 5],
+ * [3, 4, 5, 6],
+ * [4, 5, 6, 7],
+ * [5, 6, 7, 8],
+ * ];
+ *
+ * // Set the range A1:D5 with some values, the range A1:D5 will be:
+ * // 1 | 2 | 3 | 4
+ * // 2 | 3 | 4 | 5
+ * // 3 | 4 | 5 | 6
+ * // 4 | 5 | 6 | 7
+ * // 5 | 6 | 7 | 8
+ * const fRange = fWorksheet.getRange('A1:D5');
+ * fRange.setValues(values);
+ * console.log(fWorksheet.getRange('A1:D5').getValues()); // [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]
+ *
+ * // Insert the empty cells into the range A1:B2 along the columns dimension, the range A1:D5 will be:
+ * // | | 1 | 2
+ * // | | 2 | 3
+ * // 3 | 4 | 5 | 6
+ * // 4 | 5 | 6 | 7
+ * // 5 | 6 | 7 | 8
+ * const fRange2 = fWorksheet.getRange('A1:B2');
+ * fRange2.insertCells(univerAPI.Enum.Dimension.COLUMNS);
+ * console.log(fWorksheet.getRange('A1:D5').getValues()); // [[null, null, 1, 2], [null, null, 2, 3], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]
+ *
+ * // Set the range A1:D5 values again, the range A1:D5 will be:
+ * // 1 | 2 | 3 | 4
+ * // 2 | 3 | 4 | 5
+ * // 3 | 4 | 5 | 6
+ * // 4 | 5 | 6 | 7
+ * // 5 | 6 | 7 | 8
+ * fRange.setValues(values);
+ *
+ * // Insert the empty cells into the range A1:B2 along the rows dimension, the range A1:D5 will be:
+ * // | | 3 | 4
+ * // | | 4 | 5
+ * // 1 | 2 | 5 | 6
+ * // 2 | 3 | 6 | 7
+ * // 3 | 4 | 7 | 8
+ * const fRange3 = fWorksheet.getRange('A1:B2');
+ * fRange3.insertCells(univerAPI.Enum.Dimension.ROWS);
+ * console.log(fWorksheet.getRange('A1:D5').getValues()); // [[null, null, 3, 4], [null, null, 4, 5], [1, 2, 5, 6], [2, 3, 6, 7], [3, 4, 7, 8]]
+ * ```
+ */
+ insertCells(shiftDimension: Dimension): void {
+ if (shiftDimension === Dimension.ROWS) {
+ this._commandService.executeCommand(InsertRangeMoveDownCommand.id, {
+ range: this._range,
+ });
+ } else {
+ this._commandService.executeCommand(InsertRangeMoveRightCommand.id, {
+ range: this._range,
+ });
+ }
+ }
+
+ /**
+ * Deletes this range of cells. Existing data in the sheet along the provided dimension is shifted towards the deleted range.
+ * @param {Dimension} shiftDimension - The dimension along which to shift existing data.
+ * @example
+ * ```ts
+ * // Assume the active sheet empty sheet.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const values = [
+ * [1, 2, 3, 4],
+ * [2, 3, 4, 5],
+ * [3, 4, 5, 6],
+ * [4, 5, 6, 7],
+ * [5, 6, 7, 8],
+ * ];
+ *
+ * // Set the range A1:D5 with some values, the range A1:D5 will be:
+ * // 1 | 2 | 3 | 4
+ * // 2 | 3 | 4 | 5
+ * // 3 | 4 | 5 | 6
+ * // 4 | 5 | 6 | 7
+ * // 5 | 6 | 7 | 8
+ * const fRange = fWorksheet.getRange('A1:D5');
+ * fRange.setValues(values);
+ * console.log(fWorksheet.getRange('A1:D5').getValues()); // [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]
+ *
+ * // Delete the range A1:B2 along the columns dimension, the range A1:D5 will be:
+ * // 3 | 4 | |
+ * // 4 | 5 | |
+ * // 3 | 4 | 5 | 6
+ * // 4 | 5 | 6 | 7
+ * // 5 | 6 | 7 | 8
+ * const fRange2 = fWorksheet.getRange('A1:B2');
+ * fRange2.deleteCells(univerAPI.Enum.Dimension.COLUMNS);
+ * console.log(fWorksheet.getRange('A1:D5').getValues()); // [[3, 4, null, null], [4, 5, null, null], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]
+ *
+ * // Set the range A1:D5 values again, the range A1:D5 will be:
+ * // 1 | 2 | 3 | 4
+ * // 2 | 3 | 4 | 5
+ * // 3 | 4 | 5 | 6
+ * // 4 | 5 | 6 | 7
+ * // 5 | 6 | 7 | 8
+ * fRange.setValues(values);
+ *
+ * // Delete the range A1:B2 along the rows dimension, the range A1:D5 will be:
+ * // 3 | 4 | 3 | 4
+ * // 4 | 5 | 4 | 5
+ * // 5 | 6 | 5 | 6
+ * // | | 6 | 7
+ * // | | 7 | 8
+ * const fRange3 = fWorksheet.getRange('A1:B2');
+ * fRange3.deleteCells(univerAPI.Enum.Dimension.ROWS);
+ * console.log(fWorksheet.getRange('A1:D5').getValues()); // [[3, 4, 3, 4], [4, 5, 4, 5], [5, 6, 5, 6], [null, null, 6, 7], [null, null, 7, 8]]
+ * ```
+ */
+ deleteCells(shiftDimension: Dimension): void {
+ if (shiftDimension === Dimension.ROWS) {
+ this._commandService.executeCommand(DeleteRangeMoveUpCommand.id, {
+ range: this._range,
+ });
+ } else {
+ this._commandService.executeCommand(DeleteRangeMoveLeftCommand.id, {
+ range: this._range,
+ });
+ }
+ }
+
+ /**
+ * Returns a copy of the range expanded `Direction.UP` and `Direction.DOWN` if the specified dimension is `Dimension.ROWS`, or `Direction.NEXT` and `Direction.PREVIOUS` if the dimension is `Dimension.COLUMNS`.
+ * The expansion of the range is based on detecting data next to the range that is organized like a table.
+ * The expanded range covers all adjacent cells with data in them along the specified dimension including the table boundaries.
+ * If the original range is surrounded by empty cells along the specified dimension, the range itself is returned.
+ * @param {Dimension} [dimension] - The dimension along which to expand the range. If not provided, the range will be expanded in both dimensions.
+ * @returns {FRange} The range's data region or a range covering each column or each row spanned by the original range.
+ * @example
+ * ```ts
+ * // Assume the active sheet is a new sheet with no data.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ *
+ * // Set the range A1:D4 with some values, the range A1:D4 will be:
+ * // | | |
+ * // | | 100 |
+ * // | 100 | | 100
+ * // | | 100 |
+ * fWorksheet.getRange('C2').setValue(100);
+ * fWorksheet.getRange('B3').setValue(100);
+ * fWorksheet.getRange('D3').setValue(100);
+ * fWorksheet.getRange('C4').setValue(100);
+ *
+ * // Get C3 data region along the rows dimension, the range will be C2:D4
+ * const range = fWorksheet.getRange('C3').getDataRegion(univerAPI.Enum.Dimension.ROWS);
+ * console.log(range.getA1Notation()); // C2:C4
+ *
+ * // Get C3 data region along the columns dimension, the range will be B3:D3
+ * const range2 = fWorksheet.getRange('C3').getDataRegion(univerAPI.Enum.Dimension.COLUMNS);
+ * console.log(range2.getA1Notation()); // B3:D3
+ *
+ * // Get C3 data region along the both dimension, the range will be B2:D4
+ * const range3 = fWorksheet.getRange('C3').getDataRegion();
+ * console.log(range3.getA1Notation()); // B2:D4
+ * ```
+ */
+ // eslint-disable-next-line complexity
+ getDataRegion(dimension?: Dimension): FRange {
+ const { startRow, startColumn, endRow, endColumn } = this._range;
+ const maxRows = this._worksheet.getMaxRows();
+ const maxColumns = this._worksheet.getMaxColumns();
+ const cellMatrix = this._worksheet.getCellMatrix();
+
+ // If the original range is surrounded by empty cells along the specified dimension, the range itself is returned.
+ let newStartRow = startRow;
+ let newStartColumn = startColumn;
+ let newEndRow = endRow;
+ let newEndColumn = endColumn;
+
+ // Four directions or dimension rows
+ if (dimension !== Dimension.COLUMNS) {
+ let topRowHasValue = false;
+ let bottomRowHasValue = false;
+
+ for (let c = startColumn; c <= endColumn; c++) {
+ if (startRow > 0 && !isNullCell(cellMatrix.getValue(startRow - 1, c))) {
+ topRowHasValue = true;
+ }
+
+ if (endRow < maxRows - 1 && !isNullCell(cellMatrix.getValue(endRow + 1, c))) {
+ bottomRowHasValue = true;
+ }
+
+ if (topRowHasValue && bottomRowHasValue) {
+ break;
+ }
+ }
+
+ if (topRowHasValue) {
+ newStartRow = startRow - 1;
+ }
+
+ if (bottomRowHasValue) {
+ newEndRow = endRow + 1;
+ }
+ }
+
+ // Four directions or dimension columns
+ if (dimension !== Dimension.ROWS) {
+ let leftColumnHasValue = false;
+ let rightColumnHasValue = false;
+
+ for (let r = startRow; r <= endRow; r++) {
+ if (startColumn > 0 && !isNullCell(cellMatrix.getValue(r, startColumn - 1))) {
+ leftColumnHasValue = true;
+ }
+
+ if (endColumn < maxColumns - 1 && !isNullCell(cellMatrix.getValue(r, endColumn + 1))) {
+ rightColumnHasValue = true;
+ }
+
+ if (leftColumnHasValue && rightColumnHasValue) {
+ break;
+ }
+ }
+
+ if (leftColumnHasValue) {
+ newStartColumn = startColumn - 1;
+ }
+
+ if (rightColumnHasValue) {
+ newEndColumn = endColumn + 1;
+ }
+ }
+
+ return this._injector.createInstance(FRange, this._workbook, this._worksheet, {
+ startRow: newStartRow,
+ startColumn: newStartColumn,
+ endRow: newEndRow,
+ endColumn: newEndColumn,
+ });
+ }
+
+ /**
+ * Returns true if the range is totally blank.
+ * @returns {boolean} true if the range is blank; false otherwise.
+ * @example
+ * ```ts
+ * // Assume the active sheet is a new sheet with no data.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * console.log(fRange.isBlank()); // true
+ *
+ * // Set the range A1:B2 with some values
+ * fRange.setValueForCell(123);
+ * console.log(fRange.isBlank()); // false
+ * ```
+ */
+ isBlank(): boolean {
+ const cellMatrix = this._worksheet.getCellMatrix();
+ const { startRow, startColumn, endRow, endColumn } = this._range;
+
+ let isBlank = true;
+
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ if (!isNullCell(cellMatrix.getValue(r, c))) {
+ isBlank = false;
+ break;
+ }
+ }
+
+ if (!isBlank) {
+ break;
+ }
+ }
+
+ return isBlank;
+ }
+
+ /**
+ * Returns a new range that is offset from this range by the given number of rows and columns (which can be negative).
+ * The new range is the same size as the original range.
+ * @param {number} rowOffset - The number of rows down from the range's top-left cell; negative values represent rows up from the range's top-left cell.
+ * @param {number} columnOffset - The number of columns right from the range's top-left cell; negative values represent columns left from the range's top-left cell.
+ * @returns {FRange} The new range.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * console.log(fRange.getA1Notation()); // A1:B2
+ *
+ * // Offset the range by 1 row and 1 column
+ * const newRange = fRange.offset(1, 1);
+ * console.log(newRange.getA1Notation()); // B2:C3
+ * ```
+ */
+ offset(rowOffset: number, columnOffset: number): FRange;
+ /**
+ * Returns a new range that is relative to the current range, whose upper left point is offset from the current range by the given rows and columns, and with the given height in cells.
+ * @param {number} rowOffset - The number of rows down from the range's top-left cell; negative values represent rows up from the range's top-left cell.
+ * @param {number} columnOffset - The number of columns right from the range's top-left cell; negative values represent columns left from the range's top-left cell.
+ * @param {number} numRows - The height in rows of the new range.
+ * @returns {FRange} The new range.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * console.log(fRange.getA1Notation()); // A1:B2
+ *
+ * // Offset the range by 1 row and 1 column, and set the height of the new range to 3
+ * const newRange = fRange.offset(1, 1, 3);
+ * console.log(newRange.getA1Notation()); // B2:C4
+ * ```
+ */
+ offset(rowOffset: number, columnOffset: number, numRows: number): FRange;
+ /**
+ * Returns a new range that is relative to the current range, whose upper left point is offset from the current range by the given rows and columns, and with the given height and width in cells.
+ * @param {number} rowOffset - The number of rows down from the range's top-left cell; negative values represent rows up from the range's top-left cell.
+ * @param {number} columnOffset - The number of columns right from the range's top-left cell; negative values represent columns left from the range's top-left cell.
+ * @param {number} numRows - The height in rows of the new range.
+ * @param {number} numColumns - The width in columns of the new range.
+ * @returns {FRange} The new range.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * console.log(fRange.getA1Notation()); // A1:B2
+ *
+ * // Offset the range by 1 row and 1 column, and set the height of the new range to 3 and the width to 3
+ * const newRange = fRange.offset(1, 1, 3, 3);
+ * console.log(newRange.getA1Notation()); // B2:D4
+ * ```
+ */
+ offset(rowOffset: number, columnOffset: number, numRows?: number, numColumns?: number): FRange {
+ const { startRow, startColumn, endRow, endColumn } = this._range;
+
+ const newStartRow = startRow + rowOffset;
+ const newStartColumn = startColumn + columnOffset;
+ const newEndRow = numRows ? newStartRow + numRows - 1 : endRow + rowOffset;
+ const newEndColumn = numColumns ? newStartColumn + numColumns - 1 : endColumn + columnOffset;
+
+ if (newStartRow < 0 || newStartColumn < 0 || newEndRow < 0 || newEndColumn < 0) {
+ throw new Error('The row or column index is out of range');
+ }
+
+ return this._injector.createInstance(FRange, this._workbook, this._worksheet, {
+ startRow: newStartRow,
+ startColumn: newStartColumn,
+ endRow: newEndRow,
+ endColumn: newEndColumn,
+ });
+ }
+
+ /**
+ * Updates the formula for this range. The given formula must be in A1 notation.
+ * @param {string} formula - A string representing the formula to set for the cell.
+ * @returns {FRange} This range instance for chaining.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1');
+ * fRange.setFormula('=SUM(A2:A5)');
+ * console.log(fRange.getFormula()); // '=SUM(A2:A5)'
+ * ```
+ */
+ setFormula(formula: string): FRange {
+ return this.setValue({
+ f: formula,
+ });
+ }
+
+ /**
+ * Sets a rectangular grid of formulas (must match dimensions of this range). The given formulas must be in A1 notation.
+ * @param {string[][]} formulas - A two-dimensional string array of formulas.
+ * @returns {FRange} This range instance for chaining.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * fRange.setFormulas([
+ * ['=SUM(A2:A5)', '=SUM(B2:B5)'],
+ * ['=SUM(A6:A9)', '=SUM(B6:B9)'],
+ * ]);
+ * console.log(fRange.getFormulas()); // [['=SUM(A2:A5)', '=SUM(B2:B5)'], ['=SUM(A6:A9)', '=SUM(B6:B9)']]
+ * ```
+ */
+ setFormulas(formulas: string[][]): FRange {
+ return this.setValues(formulas.map((row) => row.map((formula) => ({ f: formula }))));
+ }
}
diff --git a/packages/sheets/src/facade/f-workbook.ts b/packages/sheets/src/facade/f-workbook.ts
index 8085278781..9a5e9fd492 100644
--- a/packages/sheets/src/facade/f-workbook.ts
+++ b/packages/sheets/src/facade/f-workbook.ts
@@ -18,7 +18,7 @@ import type { CommandListener, CustomData, ICommandInfo, IDisposable, IRange, IW
import type { ISetDefinedNameMutationParam } from '@univerjs/engine-formula';
import type { IRangeThemeStyleJSON, ISetSelectionsOperationParams, ISheetCommandSharedParams } from '@univerjs/sheets';
import type { FontLine as _FontLine } from './f-range';
-import { ICommandService, ILogService, Inject, Injector, IPermissionService, IResourceLoaderService, IUniverInstanceService, LocaleService, mergeWorksheetSnapshotWithDefault, RedoCommand, toDisposable, UndoCommand, UniverInstanceType } from '@univerjs/core';
+import { ICommandService, ILogService, Inject, Injector, IPermissionService, IResourceLoaderService, IUniverInstanceService, LocaleService, mergeWorksheetSnapshotWithDefault, RANGE_TYPE, RedoCommand, toDisposable, UndoCommand, UniverInstanceType } from '@univerjs/core';
import { FBaseInitialable } from '@univerjs/core/facade';
import { IDefinedNamesService } from '@univerjs/engine-formula';
import { CopySheetCommand, getPrimaryForRange, InsertSheetCommand, RangeThemeStyle, RegisterWorksheetRangeThemeStyleCommand, RemoveSheetCommand, SCOPE_WORKBOOK_VALUE_DEFINED_NAME, SetDefinedNameCommand, SetSelectionsOperation, SetWorksheetActiveOperation, SetWorksheetOrderCommand, SheetRangeThemeService, SheetsSelectionsService, UnregisterWorksheetRangeThemeStyleCommand, WorkbookEditablePermission } from '@univerjs/sheets';
@@ -546,6 +546,31 @@ export class FWorkbook extends FBaseInitialable {
return this._injector.createInstance(FRange, this._workbook, activeSheet, active.range);
}
+ /**
+ * Returns the active cell in this spreadsheet.
+ * @returns {FRange | null} The active cell
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * console.log(fWorkbook.getActiveCell().getA1Notation());
+ * ```
+ */
+ getActiveCell(): FRange | null {
+ const activeSheet = this._workbook.getActiveSheet();
+ const selections = this._selectionManagerService.getCurrentSelections();
+ const active = selections.find((selection) => !!selection.primary);
+ if (!active) {
+ return null;
+ }
+
+ const cell: IRange = {
+ ...active.primary!,
+ rangeType: RANGE_TYPE.NORMAL,
+ };
+
+ return this._injector.createInstance(FRange, this._workbook, activeSheet, cell);
+ }
+
/**
* Deletes the currently active sheet.
* @returns {boolean} true if the sheet was deleted, false otherwise
diff --git a/packages/sheets/src/facade/f-worksheet.ts b/packages/sheets/src/facade/f-worksheet.ts
index 28a496d698..874d43b000 100644
--- a/packages/sheets/src/facade/f-worksheet.ts
+++ b/packages/sheets/src/facade/f-worksheet.ts
@@ -14,20 +14,20 @@
* limitations under the License.
*/
-import type { CustomData, ICellData, IColumnData, IColumnRange, IDisposable, IFreeze, IObjectArrayPrimitiveType, IRange, IRowData, IRowRange, IStyleData, Nullable, Workbook, Worksheet } from '@univerjs/core';
+import type { CellValue, CustomData, ICellData, IColumnData, IColumnRange, IDisposable, IFreeze, IObjectArrayPrimitiveType, IRange, IRowData, IRowRange, IStyleData, Nullable, Workbook, Worksheet } from '@univerjs/core';
import type { ISetColDataCommandParams, ISetGridlinesColorCommandParams, ISetRangeValuesMutationParams, ISetRowDataCommandParams, ISetTextWrapCommandParams, IToggleGridlinesCommandParams } from '@univerjs/sheets';
import type { FDefinedName } from './f-defined-name';
import type { FWorkbook } from './f-workbook';
import { BooleanNumber, Direction, ICommandService, ILogService, Inject, Injector, ObjectMatrix, RANGE_TYPE, WrapStrategy } from '@univerjs/core';
import { FBaseInitialable } from '@univerjs/core/facade';
import { deserializeRangeWithSheet } from '@univerjs/engine-formula';
-import { CancelFrozenCommand, ClearSelectionAllCommand, ClearSelectionContentCommand, ClearSelectionFormatCommand, copyRangeStyles, InsertColByRangeCommand, InsertRowByRangeCommand, MoveColsCommand, MoveRowsCommand, RemoveColByRangeCommand, RemoveRowByRangeCommand, SetColDataCommand, SetColHiddenCommand, SetColWidthCommand, SetFrozenCommand, SetGridlinesColorCommand, SetRangeValuesMutation, SetRowDataCommand, SetRowHeightCommand, SetRowHiddenCommand, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetTabColorCommand, SetTextWrapCommand, SetWorksheetDefaultStyleMutation, SetWorksheetHideCommand, SetWorksheetNameCommand, SetWorksheetRowIsAutoHeightCommand, SetWorksheetRowIsAutoHeightMutation, SetWorksheetShowCommand, SheetsSelectionsService, ToggleGridlinesCommand } from '@univerjs/sheets';
+import { AppendRowCommand, CancelFrozenCommand, ClearSelectionAllCommand, ClearSelectionContentCommand, ClearSelectionFormatCommand, copyRangeStyles, InsertColByRangeCommand, InsertRowByRangeCommand, MoveColsCommand, MoveRowsCommand, RemoveColByRangeCommand, RemoveRowByRangeCommand, SetColDataCommand, SetColHiddenCommand, SetColWidthCommand, SetFrozenCommand, SetGridlinesColorCommand, SetRangeValuesMutation, SetRowDataCommand, SetRowHeightCommand, SetRowHiddenCommand, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetTabColorCommand, SetTextWrapCommand, SetWorksheetDefaultStyleMutation, SetWorksheetHideCommand, SetWorksheetNameCommand, SetWorksheetRowIsAutoHeightCommand, SetWorksheetRowIsAutoHeightMutation, SetWorksheetShowCommand, SheetsSelectionsService, ToggleGridlinesCommand } from '@univerjs/sheets';
import { FDefinedNameBuilder } from './f-defined-name';
import { FRange } from './f-range';
import { FSelection } from './f-selection';
-import { covertToColRange, covertToRowRange } from './utils';
+import { covertCellValue, covertToColRange, covertToRowRange } from './utils';
-interface IFacadeClearOptions {
+export interface IFacadeClearOptions {
contentsOnly?: boolean;
formatOnly?: boolean;
}
@@ -754,7 +754,7 @@ export class FWorksheet extends FBaseInitialable {
/**
* Scrolling sheet to make specific rows visible.
* @param {number} rowIndex - The starting index of the rows
- * @param {number} numRow - The number of rows
+ * @param {number} numRows - The number of rows
* @returns {FWorksheet} This worksheet instance for chaining
* @example
* ```typescript
@@ -765,12 +765,12 @@ export class FWorksheet extends FBaseInitialable {
* fWorksheet.showRows(0);
* ```
*/
- showRows(rowIndex: number, numRow: number = 1): FWorksheet {
+ showRows(rowIndex: number, numRows: number = 1): FWorksheet {
const unitId = this._workbook.getUnitId();
const subUnitId = this._worksheet.getSheetId();
const range: IRange = {
startRow: rowIndex,
- endRow: rowIndex + numRow - 1,
+ endRow: rowIndex + numRows - 1,
startColumn: 0,
endColumn: this._worksheet.getColumnCount() - 1,
rangeType: RANGE_TYPE.ROW,
@@ -897,6 +897,27 @@ export class FWorksheet extends FBaseInitialable {
return this;
}
+ /**
+ * Gets the height in pixels of the given row.
+ * @param {number} rowPosition - The position of the row to examine. index starts at 0.
+ * @returns {number} The height in pixels of the given row.
+ * @example
+ * ```typescript
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ *
+ * // Set the value of the cell A1 to 'Hello, Univer!', set the font size to 30 and font weight to bold
+ * const fRange = fWorksheet.getRange('A1');
+ * fRange.setValue('Hello, Univer!').setFontSize(30).setFontWeight('bold');
+ *
+ * // Get the height of the first row
+ * console.log(fWorksheet.getRowHeight(0));
+ * ```
+ */
+ getRowHeight(rowPosition: number): number {
+ return this._worksheet.getRowHeight(rowPosition);
+ }
+
/**
* Sets the height of the given rows to auto.
* @param {number} startRow - The starting row position to change
@@ -1319,7 +1340,7 @@ export class FWorksheet extends FBaseInitialable {
/**
* Show one or more consecutive columns starting at the given index. Use 0-index for this method
* @param {number} columnIndex - The starting index of the columns to unhide
- * @param {number} numColumn - The number of columns to unhide
+ * @param {number} numColumns - The number of columns to unhide
* @returns {FWorksheet} This sheet, for chaining
* @example
* ```typescript
@@ -1330,14 +1351,14 @@ export class FWorksheet extends FBaseInitialable {
* fWorksheet.showColumns(0, 1);
* ```
*/
- showColumns(columnIndex: number, numColumn: number = 1): FWorksheet {
+ showColumns(columnIndex: number, numColumns: number = 1): FWorksheet {
const unitId = this._workbook.getUnitId();
const subUnitId = this._worksheet.getSheetId();
const range: IRange = {
startRow: 0,
endRow: this._worksheet.getRowCount() - 1,
startColumn: columnIndex,
- endColumn: columnIndex + numColumn - 1,
+ endColumn: columnIndex + numColumns - 1,
rangeType: RANGE_TYPE.COLUMN,
};
@@ -1401,6 +1422,30 @@ export class FWorksheet extends FBaseInitialable {
return this;
}
+ /**
+ * Gets the width in pixels of the given column.
+ * @param {number} columnPosition - The position of the column to examine. index starts at 0.
+ * @returns {number} The width of the column in pixels
+ * @example
+ * ```typescript
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ *
+ * // Set the long text value in cell A1
+ * const fRange = fWorksheet.getRange('A1');
+ * fRange.setValue('Whenever it is a damp, drizzly November in my soul...');
+ *
+ * // Set the column A to a width which fits the text
+ * fWorksheet.autoResizeColumn(0);
+ *
+ * // Get the width of the column A
+ * console.log(fWorksheet.getColumnWidth(0));
+ * ```
+ */
+ getColumnWidth(columnPosition: number): number {
+ return this._worksheet.getColumnWidth(columnPosition);
+ }
+
// #endregion
/**
@@ -1536,6 +1581,19 @@ export class FWorksheet extends FBaseInitialable {
return this;
}
+ /**
+ * Returns the active cell in this sheet.
+ * @returns {FRange | null} The active cell
+ * @example
+ * ```typescript
+ * const fWorkSheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ * console.log(fWorkSheet.getActiveCell().getA1Notation());
+ * ```
+ */
+ getActiveCell(): FRange | null {
+ return this._fWorkbook.getActiveCell();
+ }
+
/**
* Sets the active selection region for this sheet.
* @param range - The range to set as the active selection
@@ -2371,4 +2429,42 @@ export class FWorksheet extends FBaseInitialable {
getColumnCustomMetadata(index: number): CustomData | undefined {
return this._worksheet.getColumnManager().getCustomMetadata(index);
}
+
+ /**
+ * Appends a row to the bottom of the current data region in the sheet. If a cell's content begins with =, it's interpreted as a formula.
+ * @param {CellValue[]} rowContents - An array of values for the new row.
+ * @returns {FWorksheet} Returns the current worksheet instance for method chaining.
+ * @example
+ * ```ts
+ * // Appends a new row with 4 columns to the bottom of the current
+ * // data region in the sheet containing the values in the array.
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorkSheet = fWorkbook.getActiveSheet();
+ * fWorkSheet.appendRow([1, 'Hello Univer', true, '=A1']);
+ * ```
+ */
+ appendRow(rowContents: CellValue[]): FWorksheet {
+ const hasValue = this._worksheet.getCellMatrix().hasValue();
+ const lastRow = this._worksheet.getLastRowWithContent();
+ const maxRows = this._worksheet.getRowCount();
+ const maxColumns = this._worksheet.getColumnCount();
+
+ const row = hasValue ? lastRow + 1 : lastRow;
+ const cellMatrix = new ObjectMatrix<ICellData>();
+
+ for (let c = 0; c < rowContents.length; c++) {
+ cellMatrix.setValue(row, c, covertCellValue(rowContents[c]));
+ }
+
+ this._commandService.syncExecuteCommand(AppendRowCommand.id, {
+ unitId: this._workbook.getUnitId(),
+ subUnitId: this._worksheet.getSheetId(),
+ cellValue: cellMatrix.getMatrix(),
+ insertRowNums: row > maxRows - 1 ? 1 : 0,
+ insertColumnNums: rowContents.length > maxColumns ? rowContents.length - maxColumns : 0,
+ maxRows,
+ maxColumns,
+ });
+ return this;
+ }
}
diff --git a/packages/sheets/src/facade/utils.ts b/packages/sheets/src/facade/utils.ts
index fb29a9b4f7..046f98264b 100644
--- a/packages/sheets/src/facade/utils.ts
+++ b/packages/sheets/src/facade/utils.ts
@@ -26,12 +26,14 @@ import {
VerticalAlign,
} from '@univerjs/core';
+export type FDefaultAlignment = 'general';
export type FHorizontalAlignment = 'left' | 'center' | 'normal';
export type FVerticalAlignment = 'top' | 'middle' | 'bottom';
/**
- *
- * @param value
+ * Transform the Facade API horizontal alignment to the Univer Core horizontal alignment.
+ * @param {FHorizontalAlignment} value - The Facade API horizontal alignment.
+ * @returns {HorizontalAlign} The Univer Core horizontal alignment.
*/
export function transformFacadeHorizontalAlignment(value: FHorizontalAlignment): HorizontalAlign {
switch (value) {
@@ -47,10 +49,11 @@ export function transformFacadeHorizontalAlignment(value: FHorizontalAlignment):
}
/**
- *
- * @param value
+ * Transform the Univer Core horizontal alignment to the Facade API horizontal alignment.
+ * @param {HorizontalAlign} value - The Univer Core horizontal alignment.
+ * @returns {FHorizontalAlignment} The Facade API horizontal alignment.
*/
-export function transformCoreHorizontalAlignment(value: HorizontalAlign): FHorizontalAlignment {
+export function transformCoreHorizontalAlignment(value: HorizontalAlign): FHorizontalAlignment | FDefaultAlignment {
switch (value) {
case HorizontalAlign.LEFT:
return 'left';
@@ -59,13 +62,14 @@ export function transformCoreHorizontalAlignment(value: HorizontalAlign): FHoriz
case HorizontalAlign.RIGHT:
return 'normal';
default:
- throw new Error(`Invalid horizontal alignment: ${value}`);
+ return 'general';
}
}
/**
- *
- * @param value
+ * Transform the Facade API vertical alignment to the Univer Core vertical alignment.
+ * @param {FVerticalAlignment} value - The Facade API vertical alignment.
+ * @returns {VerticalAlign} The Univer Core vertical alignment.
*/
export function transformFacadeVerticalAlignment(value: FVerticalAlignment): VerticalAlign {
switch (value) {
@@ -81,10 +85,11 @@ export function transformFacadeVerticalAlignment(value: FVerticalAlignment): Ver
}
/**
- *
- * @param value
+ * Transform the Univer Core vertical alignment to the Facade API vertical alignment.
+ * @param {VerticalAlign} value - The Univer Core vertical alignment.
+ * @returns {FVerticalAlignment} The Facade API vertical alignment.
*/
-export function transformCoreVerticalAlignment(value: VerticalAlign): FVerticalAlignment {
+export function transformCoreVerticalAlignment(value: VerticalAlign): FVerticalAlignment | FDefaultAlignment {
switch (value) {
case VerticalAlign.TOP:
return 'top';
@@ -93,14 +98,14 @@ export function transformCoreVerticalAlignment(value: VerticalAlign): FVerticalA
case VerticalAlign.BOTTOM:
return 'bottom';
default:
- throw new Error(`Invalid vertical alignment: ${value}`);
+ return 'general';
}
}
/**
* Covert cell value to cell data.
- * @param value
- * @returns
+ * @param {CellValue | ICellData} value - The cell value.
+ * @returns {ICellData} The cell data.
*/
export function covertCellValue(value: CellValue | ICellData): ICellData {
if (isFormulaString(value)) {
@@ -127,9 +132,9 @@ export function covertCellValue(value: CellValue | ICellData): ICellData {
/**
* Covert cell value array or matrix to cell data.
- * @param value
- * @param range
- * @returns
+ * @param {CellValue[][] | IObjectMatrixPrimitiveType<CellValue> | ICellData[][] | IObjectMatrixPrimitiveType<ICellData>} value - The cell value array or matrix.
+ * @param {IRange} range - The range.
+ * @returns {IObjectMatrixPrimitiveType<ICellData>} The cell data matrix.
*/
export function covertCellValues(
value:
@@ -159,9 +164,10 @@ export function covertCellValues(
}
/**
- *
- * @param mergeInfo
- * @param range
+ * Judge whether the range is merged.
+ * @param {IRangeWithCoord} mergeInfo - The merge info.
+ * @param {IRange} range - The range.
+ * @returns {boolean} Whether the range is merged.
*/
export function isCellMerged(mergeInfo: IRangeWithCoord, range: IRange): boolean {
if (!isSingleCell(mergeInfo, range)) {
@@ -171,9 +177,10 @@ export function isCellMerged(mergeInfo: IRangeWithCoord, range: IRange): boolean
}
/**
- *
- * @param mergeInfo
- * @param range
+ * Judge whether the range is single cell.
+ * @param {IRangeWithCoord} mergeInfo - The merge info.
+ * @param {IRange} range - The range.
+ * @returns {boolean} Whether the range is single cell.
*/
export function isSingleCell(mergeInfo: IRangeWithCoord, range: IRange): boolean {
return mergeInfo.startColumn === range.startColumn
@@ -183,9 +190,10 @@ export function isSingleCell(mergeInfo: IRangeWithCoord, range: IRange): boolean
}
/**
- *
- * @param range
- * @param worksheet
+ * Covert the range to row range.
+ * @param {IRange} range - The range.
+ * @param {Worksheet} worksheet - The worksheet.
+ * @returns {IRange} The row range.
*/
export function covertToRowRange(range: IRange, worksheet: Worksheet): IRange {
return {
@@ -198,9 +206,10 @@ export function covertToRowRange(range: IRange, worksheet: Worksheet): IRange {
}
/**
- *
- * @param range
- * @param worksheet
+ * Covert the range to column range.
+ * @param {IRange} range - The range.
+ * @param {Worksheet} worksheet - The worksheet.
+ * @returns {IRange} The column range.
*/
export function covertToColRange(range: IRange, worksheet: Worksheet): IRange {
return {
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index a0e3c65748..012ec727df 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -207,6 +207,7 @@ export {
} from './commands/commands/add-worksheet-merge.command';
export { SetWorksheetRangeThemeStyleCommand } from './commands/commands/add-worksheet-range-theme.command';
export { DeleteWorksheetRangeThemeStyleCommand } from './commands/commands/delete-worksheet-range-theme.command';
+export { AppendRowCommand, type IAppendRowCommandParams } from './commands/commands/append-row.command';
export { ClearSelectionAllCommand } from './commands/commands/clear-selection-all.command';
export { ClearSelectionContentCommand } from './commands/commands/clear-selection-content.command';
export { ClearSelectionFormatCommand } from './commands/commands/clear-selection-format.command';
@@ -236,6 +237,7 @@ export {
InsertRowByRangeCommand,
InsertRowCommand,
} from './commands/commands/insert-row-col.command';
+
export { type IInsertSheetCommandParams, InsertSheetCommand } from './commands/commands/insert-sheet.command';
export { getMoveRangeUndoRedoMutations, type IMoveRangeCommandParams, MoveRangeCommand } from './commands/commands/move-range.command';
export {
@@ -447,4 +449,5 @@ export { SCOPE_WORKBOOK_VALUE_DEFINED_NAME } from './controllers/defined-name-da
export type { ICellOverGridPosition, ISheetOverGridPosition } from './basics/cell-position';
export { SheetSkeletonService } from './skeleton/skeleton.service';
+
// #endregion