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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(textsplit): support text split util function (#4302)
VicKunf5d1c794e478
diff --git a/packages/sheets/src/basics/split-range-text.ts b/packages/sheets/src/basics/split-range-text.tsnew file mode 100644index 0000000000..3060fd82b3--- /dev/null+++ b/packages/sheets/src/basics/split-range-text.ts@@ -0,0 +1,241 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICellData, IDocumentData, IRange, Nullable, Worksheet } from '@univerjs/core';+import { CellValueType, Range } from '@univerjs/core';++/**+ * The default delimiter to split the text.+ */+export enum SplitDelimiterEnum {+ /**+ * The tab character+ */+ Tab = 1,+ /**+ * The comma character+ */+ Comma = 2,+ /**+ * The semicolon character+ */+ Semicolon = 4,+ /**+ * The space character+ */+ Space = 8,+ /**+ * The custom delimiter+ */+ Custom = 16,+}++class DelimiterCounter {+ private _tabCount = 0;+ private _commaCount = 0;+ private _semicolonCount = 0;+ private _spaceCount = 0;++ add(delimiter: string) {+ switch (delimiter) {+ case '\t':+ this._tabCount++;+ break;+ case ',':+ this._commaCount++;+ break;+ case ';':+ this._semicolonCount++;+ break;+ case ' ':+ this._spaceCount++;+ break;+ default:+ break;+ }+ }++ update(cellText: string | undefined) {+ if (cellText && typeof cellText === 'string') {+ if (cellText.includes('\t')) {+ this._tabCount++;+ }+ if (cellText.includes(',')) {+ this._commaCount++;+ }+ if (cellText.includes(';')) {+ this._semicolonCount++;+ }+ if (cellText.trim().includes(' ')) {+ this._spaceCount++;+ }+ }+ }++ getDelimiter() {+ const maxCount = Math.max(this._tabCount, this._commaCount, this._semicolonCount, this._spaceCount);++ if (maxCount === 0) {+ return SplitDelimiterEnum.Tab;+ }+ if (maxCount === this._tabCount) {+ return SplitDelimiterEnum.Tab;+ }+ if (maxCount === this._commaCount) {+ return SplitDelimiterEnum.Comma;+ }+ if (maxCount === this._semicolonCount) {+ return SplitDelimiterEnum.Semicolon;+ }+ if (maxCount === this._spaceCount) {+ return SplitDelimiterEnum.Space;+ }+ return SplitDelimiterEnum.Tab;+ }+}++function getDelimiterRegexItem(delimiter: SplitDelimiterEnum, treatMultipleDelimitersAsOne: boolean, customDelimiter?: string) {+ const delimiterList = [];++ if (customDelimiter !== undefined && (delimiter & SplitDelimiterEnum.Custom) > 0) {+ delimiterList.push(customDelimiter);+ }+ if ((delimiter & SplitDelimiterEnum.Tab) > 0) {+ delimiterList.push('\t');+ }+ if ((delimiter & SplitDelimiterEnum.Comma) > 0) {+ delimiterList.push(',');+ }+ if ((delimiter & SplitDelimiterEnum.Semicolon) > 0) {+ delimiterList.push(';');+ }+ if ((delimiter & SplitDelimiterEnum.Space) > 0) {+ delimiterList.push(' ');+ }++ let str = '';+ for (const delimiter of delimiterList) {+ str += escapeRegExp(delimiter);+ }+ let allStr = '['.concat(str, ']');++ if (treatMultipleDelimitersAsOne) {+ allStr += '+';+ }++ return new RegExp(allStr);+}++function escapeRegExp(str: string) {+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++const getStringFromDataStream = (data: IDocumentData): string => {+ const dataStream = data.body?.dataStream.replace(/\r\n$/, '') || '';+ return dataStream;+};++function cellValueToString(cellData: Nullable<ICellData>) {+ if (cellData === null || cellData === undefined) {+ return undefined;+ }++ if (cellData.p) {+ return getStringFromDataStream(cellData.p);+ }++ if (cellData.v && typeof cellData.v === 'string') {+ return cellData.v;+ }++ if (cellData.t && (cellData.t === CellValueType.FORCE_STRING || cellData.t === CellValueType.STRING)) {+ return String(cellData.v);+ }++ return undefined;+}++interface ISplitRangeTextResult {+ rs: (string[] | undefined)[];+ maxLength: number;+ lastRow: number;+}++/**+ * Split the text in the range into a two-dimensional array.+ * @param {Worksheet} sheet The worksheet which range belongs to.+ * @param {IRange} range The range to split.+ * @param {SplitDelimiterEnum} [delimiter] The delimiter to split the text.+ * @param {string} [customDelimiter] The custom delimiter to split the text. An error will be thrown if customDelimiter is not a character.+ * @param {boolean} [treatMultipleDelimitersAsOne] split multiple delimiters as one.+ * @returns {ISplitRangeTextResult} The two-dimensional array of the split text and max column length.+ */+export function splitRangeText(sheet: Worksheet, range: IRange, delimiter?: SplitDelimiterEnum, customDelimiter?: string, treatMultipleDelimitersAsOne: boolean = false): ISplitRangeTextResult {+ const sourceRange = Range.transformRange(range, sheet);+ const { startColumn, startRow, endColumn, endRow } = sourceRange;++ if (startColumn !== endColumn) {+ throw new Error('The range must be in the same column.');+ }++ if ((delimiter && (delimiter & SplitDelimiterEnum.Custom) > 0) && (customDelimiter === undefined || customDelimiter.length !== 1)) {+ throw new Error('The custom delimiter must a character.');+ }++ const needAutoDelimiter = delimiter === undefined;+ const delimiterCounter = needAutoDelimiter ? new DelimiterCounter() : null;+ const textList = [];++ // collect delimiter and text values+ for (let i = startRow; i <= endRow; i++) {+ const cell = sheet.getCell(i, startColumn);+ const cellString = cellValueToString(cell);+ textList.push(cellString);+ if (delimiterCounter) {+ delimiterCounter.update(cellString);+ }+ }++ const useDelimiter = needAutoDelimiter ? delimiterCounter!.getDelimiter() : delimiter;+ const useDelimiterRegex = getDelimiterRegexItem(useDelimiter, treatMultipleDelimitersAsOne, customDelimiter);++ let maxLength = -1;+ let lastRow = 0;+ let index = 0;+ const rs = [];++ for (const text of textList) {+ if (text !== undefined) {+ const cols = String(text).split(useDelimiterRegex);+ if (maxLength < 0) {+ maxLength = cols.length;+ } else {+ maxLength = Math.max(maxLength, cols.length);+ }+ rs.push(cols);+ lastRow = index;+ } else {+ rs.push(undefined);+ }+ index++;+ }++ return {+ rs,+ maxLength: maxLength === -1 ? 0 : maxLength,+ lastRow,+ };+}diff --git a/packages/sheets/src/commands/commands/split-text-to-columns.command.ts b/packages/sheets/src/commands/commands/split-text-to-columns.command.tsnew file mode 100644index 0000000000..c2219986b9--- /dev/null+++ b/packages/sheets/src/commands/commands/split-text-to-columns.command.ts@@ -0,0 +1,148 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IAccessor, ICellData, IRange, Nullable, Workbook } from '@univerjs/core';+import type { IInsertColMutationParams, IRemoveColMutationParams } from '../../basics';+import type { ISetRangeValuesMutationParams } from '../mutations/set-range-values.mutation';++import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, ObjectMatrix, Range, sequenceExecute, UniverInstanceType } from '@univerjs/core';+import { type SplitDelimiterEnum, splitRangeText } from '../../basics/split-range-text';+import { InsertColMutation, InsertColMutationUndoFactory } from '../mutations/insert-row-col.mutation';+import { RemoveColMutation } from '../mutations/remove-row-col.mutation';+import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../mutations/set-range-values.mutation';+import { getSheetCommandTarget } from './utils/target-util';++export interface ISplitTextToColumnsCommandParams {+ unitId: string;+ subUnitId: string;+ range: IRange;+ delimiter?: SplitDelimiterEnum;+ customDelimiter?: string;+ treatMultipleDelimitersAsOne?: boolean;+}++export const SplitTextToColumnsCommand = {+ type: CommandType.COMMAND,+ id: 'sheet.command.split-text-to-columns',+ // eslint-disable-next-line max-lines-per-function+ handler: async (accessor: IAccessor, params: ISplitTextToColumnsCommandParams) => {+ const { unitId, subUnitId, range, delimiter, customDelimiter, treatMultipleDelimitersAsOne } = params;++ const commandService = accessor.get(ICommandService);++ const univerInstanceService = accessor.get(IUniverInstanceService);+ const undoRedoService = accessor.get(IUndoRedoService);++ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));+ if (!target) return false;+ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ if (!workbook) return false;+ const worksheet = workbook.getSheetBySheetId(subUnitId);+ if (!worksheet) return false;++ const { lastRow, rs, maxLength } = splitRangeText(worksheet, range, delimiter, customDelimiter, treatMultipleDelimitersAsOne);+ const maxColumn = worksheet.getColumnCount();+ const { startColumn } = Range.transformRange(range, worksheet);++ if (range.startColumn !== range.endColumn) {+ return false;+ }++ const redoMutations = [];+ const undoMutations = [];++ // insert columns if needed+ const insertColCount = startColumn + maxLength + 1 - maxColumn;+ if (insertColCount > 0) {+ const insertColParams: IInsertColMutationParams = {+ unitId,+ subUnitId,+ range: {+ startRow: 0,+ endRow: worksheet.getRowCount() - 1,+ startColumn: maxColumn - 1,+ endColumn: maxColumn - 1 + insertColCount,+ },++ };++ redoMutations.push({+ id: InsertColMutation.id,+ params: insertColParams,+ });++ const undoColInsertionParams: IRemoveColMutationParams = InsertColMutationUndoFactory(+ accessor,+ insertColParams+ );++ undoMutations.push({ id: RemoveColMutation.id, params: undoColInsertionParams });+ }++ // set values+ const destRange = {+ startRow: range.startRow,+ endRow: lastRow,+ startColumn,+ endColumn: startColumn + maxLength,+ };+ const cellValue = new ObjectMatrix<Nullable<ICellData>>();+ for (let i = destRange.startRow; i <= destRange.endRow; i++) {+ for (let j = destRange.startColumn; j <= destRange.endColumn; j++) {+ const values = rs[i - destRange.startRow];+ if (j === 0 && values?.length === 1) {+ cellValue.setValue(i, j, worksheet.getCell(i, j));+ } else {+ cellValue.setValue(i, j, {+ v: values?.[j - destRange.startColumn] || null,+ p: null,+ f: null,+ si: null,+ custom: null,+ });+ }+ }+ }++ const setValuesParams: ISetRangeValuesMutationParams = {+ unitId,+ subUnitId,+ cellValue: cellValue.clone(),+ };+ const undoSetValuesParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(accessor, setValuesParams);++ redoMutations.push({+ id: SetRangeValuesMutation.id,+ params: setValuesParams,+ });+ undoMutations.unshift({+ id: SetRangeValuesMutation.id,+ params: undoSetValuesParams,+ });++ const result = sequenceExecute(redoMutations, commandService).result;+ if (result) {+ undoRedoService.pushUndoRedo({+ unitID: unitId,+ undoMutations,+ redoMutations,+ });+ return true;+ }++ return false;+ },+};diff --git a/packages/sheets/src/controllers/basic-worksheet.controller.ts b/packages/sheets/src/controllers/basic-worksheet.controller.tsindex 90473cf6ce..c4b37a7053 100644--- a/packages/sheets/src/controllers/basic-worksheet.controller.ts+++ b/packages/sheets/src/controllers/basic-worksheet.controller.ts@@ -98,6 +98,7 @@ import {SetWorksheetRowIsAutoHeightCommand,} from '../commands/commands/set-worksheet-row-height.command';import { SetWorksheetShowCommand } from '../commands/commands/set-worksheet-show.command';+import { SplitTextToColumnsCommand } from '../commands/commands/split-text-to-columns.command';import { ToggleCellCheckboxCommand } from '../commands/commands/toggle-checkbox.command';import { ToggleGridlinesCommand } from '../commands/commands/toggle-gridlines.command';import { AddRangeProtectionMutation } from '../commands/mutations/add-range-protection.mutation';@@ -112,12 +113,12 @@ import { MoveRangeMutation } from '../commands/mutations/move-range.mutation';import { MoveColsMutation, MoveRowsMutation } from '../commands/mutations/move-rows-cols.mutation';import { RemoveNumfmtMutation, SetNumfmtMutation } from '../commands/mutations/numfmt-mutation';import { RemoveColMutation, RemoveRowMutation } from '../commands/mutations/remove-row-col.mutation';-import { RemoveSheetMutation } from '../commands/mutations/remove-sheet.mutation';+import { RemoveSheetMutation } from '../commands/mutations/remove-sheet.mutation';import { RemoveWorksheetMergeMutation } from '../commands/mutations/remove-worksheet-merge.mutation';import { ReorderRangeMutation } from '../commands/mutations/reorder-range.mutation';-import { SetColDataMutation } from '../commands/mutations/set-col-data.mutation';+import { SetColDataMutation } from '../commands/mutations/set-col-data.mutation';import { SetColHiddenMutation, SetColVisibleMutation } from '../commands/mutations/set-col-visible.mutation';import { SetFrozenMutation } from '../commands/mutations/set-frozen.mutation';import { SetGridlinesColorMutation } from '../commands/mutations/set-gridlines-color.mutation';@@ -300,6 +301,8 @@ export class BasicWorksheetController extends Disposable implements IDisposableToggleCellCheckboxCommand,SetWorksheetDefaultStyleMutation,SetWorksheetDefaultStyleCommand,++ SplitTextToColumnsCommand,].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));}diff --git a/packages/sheets/src/facade/f-range.ts b/packages/sheets/src/facade/f-range.tsindex 82769b77e5..210c2f7cb4 100644--- a/packages/sheets/src/facade/f-range.ts+++ b/packages/sheets/src/facade/f-range.ts@@ -15,11 +15,11 @@*/import type { CellValue, ICellData, IColorStyle, IObjectMatrixPrimitiveType, IRange, IStyleData, ITextDecoration, Nullable, Workbook, Worksheet } from '@univerjs/core';-import type { ISetHorizontalTextAlignCommandParams, ISetStyleCommandParams, ISetTextWrapCommandParams, ISetVerticalTextAlignCommandParams, IStyleTypeValue } from '@univerjs/sheets';+import type { ISetHorizontalTextAlignCommandParams, ISetStyleCommandParams, ISetTextWrapCommandParams, ISetVerticalTextAlignCommandParams, IStyleTypeValue, SplitDelimiterEnum } from '@univerjs/sheets';import type { FHorizontalAlignment, FVerticalAlignment } from './utils';import { BooleanNumber, Dimension, FBase, ICommandService, Inject, Injector, Rectangle, Tools, WrapStrategy } from '@univerjs/core';import { FormulaDataModel } from '@univerjs/engine-formula';-import { addMergeCellsUtil, getAddMergeMutationRangeByType, RemoveWorksheetMergeCommand, SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand } from '@univerjs/sheets';+import { addMergeCellsUtil, getAddMergeMutationRangeByType, RemoveWorksheetMergeCommand, SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand, SplitTextToColumnsCommand } from '@univerjs/sheets';import { FWorkbook } from './f-workbook';import { covertCellValue, covertCellValues, transformCoreHorizontalAlignment, transformCoreVerticalAlignment, transformFacadeHorizontalAlignment, transformFacadeVerticalAlignment } from './utils';@@ -676,7 +676,7 @@ export class FRange extends FBase {const mergeInfo = this._worksheet.getMergedCell(this._range.startRow, this._range.startColumn);// the range is a merge cell or single cellconst valid = (mergeInfo && Rectangle.equals(mergeInfo, this._range)) ||- (!mergeInfo && this._range.startRow === this._range.endRow && this._range.startColumn === this._range.endColumn);+ (!mergeInfo && this._range.startRow === this._range.endRow && this._range.startColumn === this._range.endColumn);if (valid) {return this.activate();@@ -684,4 +684,72 @@ export class FRange extends FBase {throw new Error('The range is not a single cell');}}++ /**+ * Splits a column of text into multiple columns based on an auto-detected delimiter.+ * @param {boolean} [treatMultipleDelimitersAsOne] Whether to treat multiple continuous delimiters as one. The default value is false.+ * @example+ * // A1:A3 has following values:+ * // A | B | C+ * // 1,2,3 | |+ * // 4,,5,6 | |+ * // After calling splitTextToColumns(true), the range will be:+ * // A | B | C+ * // 1 | 2 | 3+ * // 4 | 5 | 6+ * // After calling splitTextToColumns(false), the range will be:+ * // A | B | C | D+ * // 1 | 2 | 3 |+ * // 4 | | 5 | 6+ */+ splitTextToColumns(treatMultipleDelimitersAsOne?: boolean): void;+ /**+ * Splits a column of text into multiple columns based on a specified delimiter.+ * @param {boolean} [treatMultipleDelimitersAsOne] Whether to treat multiple continuous delimiters as one. The default value is false.+ * @param {SplitDelimiterEnum} [delimiter] The delimiter to use to split the text. The default delimiter is Tab(1)、Comma(2)、Semicolon(4)、Space(8)、Custom(16).A delimiter like 6 (SplitDelimiterEnum.Comma|SplitDelimiterEnum.Semicolon) means using Comma and Semicolon to split the text.+ * @returns {void}+ */+ splitTextToColumns(treatMultipleDelimitersAsOne?: boolean, delimiter?: SplitDelimiterEnum): void;+ /**+ * Splits a column of text into multiple columns based on a custom specified delimiter.+ * @param {boolean} [treatMultipleDelimitersAsOne] Whether to treat multiple continuous delimiters as one. The default value is false.+ * @param {SplitDelimiterEnum} [delimiter] The delimiter to use to split the text. The default delimiter is Tab(1)、Comma(2)、Semicolon(4)、Space(8)、Custom(16).A delimiter like 6 (SplitDelimiterEnum.Comma|SplitDelimiterEnum.Semicolon) means using Comma and Semicolon to split the text.+ * @param {string} [customDelimiter] The custom delimiter to split the text. An error will be thrown if custom delimiter is set but the customDelimiter is not a character.+ * @example Show how to split text to columns with combined delimiter. The bit operations are used to combine the delimiters.+ * // A1:A3 has following values:+ * // A | B | C+ * // 1;;2;3 | |+ * // 1;,2;3 | |+ * // After calling splitTextToColumns(false, SplitDelimiterEnum.Semicolon|SplitDelimiterEnum.Comma), the range will be:+ * // A | B | C | D+ * // 1 | | 2 | 3+ * // 1 | | 2 | 3+ * // After calling splitTextToColumns(true, SplitDelimiterEnum.Semicolon|SplitDelimiterEnum.Comma), the range will be:+ * // A | B | C+ * // 1 | 2 | 3+ * // 1 | 2 | 3+ * @example Show how to split text to columns with custom delimiter+ * // A1:A3 has following values:+ * // A | B | C+ * // 1#2#3 | |+ * // 4##5#6 | |+ * // After calling splitTextToColumns(false, SplitDelimiterEnum.Custom, '#'), the range will be:+ * // A | B | C | D+ * // 1 | 2 | 3 |+ * // 4 | | 5 | 6+ * // After calling splitTextToColumns(true, SplitDelimiterEnum.Custom, '#'), the range will be:+ * // A | B | C+ * // 1 | 2 | 3+ * // 4 | 5 | 6+ */+ splitTextToColumns(treatMultipleDelimitersAsOne?: boolean, delimiter?: SplitDelimiterEnum, customDelimiter?: string): void {+ this._commandService.executeCommand(SplitTextToColumnsCommand.id, {+ unitId: this._workbook.getUnitId(),+ subUnitId: this._worksheet.getSheetId(),+ range: this._range,+ delimiter,+ customDelimiter,+ treatMultipleDelimitersAsOne,+ });+ }}diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.tsindex 1551a6e922..bf59d8e19b 100644--- a/packages/sheets/src/index.ts+++ b/packages/sheets/src/index.ts@@ -97,6 +97,8 @@ export { AddMergeRedoSelectionsOperationFactory, AddMergeUndoSelectionsOperationexport type { FormatType } from './services/numfmt/type';export { expandToContinuousRange } from './basics/expand-range';+export { splitRangeText } from './basics/split-range-text';+export type { SplitDelimiterEnum } from './basics/split-range-text';export { getNextPrimaryCell } from './services/selections/move-active-cell-util';export { ExclusiveRangeService, IExclusiveRangeService } from './services/exclusive-range/exclusive-range-service';@@ -319,6 +321,10 @@ export {SetWorksheetRowIsAutoHeightCommand,} from './commands/commands/set-worksheet-row-height.command';export { SetWorksheetShowCommand } from './commands/commands/set-worksheet-show.command';++export { SplitTextToColumnsCommand } from './commands/commands/split-text-to-columns.command';+export type { ISplitTextToColumnsCommandParams } from './commands/commands/split-text-to-columns.command';+export type { ISetWorksheetShowCommandParams } from './commands/commands/set-worksheet-show.command';export { AddRangeProtectionMutation, FactoryAddRangeProtectionMutation, type IAddRangeProtectionMutationParams } from './commands/mutations/add-range-protection.mutation';export { SetProtectionCommand } from './commands/commands/set-protection.command';