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
chore: demo add import-csv-plugin (#5067)
wpxp123456f556c6581209
diff --git a/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts b/e2e/visual-comparison/docs/docs-visual-comparison.spec.tsindex be8b9efc65..8be10b2b51 100644--- a/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts+++ b/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts@@ -31,6 +31,6 @@ test('diff default doc content', async ({ page }) => {await page.evaluate(() => window.E2EControllerAPI.loadDefaultDoc());await page.waitForTimeout(5000);- await expect(page).toHaveScreenshot(generateSnapshotName('default-doc'), { maxDiffPixels: 30 });+ await expect(page).toHaveScreenshot(generateSnapshotName('default-doc'), { maxDiffPixels: 100 });expect(errored).toBeFalsy();});diff --git a/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts b/e2e/visual-comparison/sheets/sheets-formula-related.spec.tsindex 3937636432..f24d5451c0 100644--- a/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts+++ b/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts@@ -131,7 +131,7 @@ test('diff formula related', async () => {const filename1 = generateSnapshotName('formula-hide-row-current-worksheet');const screenshot1 = await page.locator(SHEET_MAIN_CANVAS_ID).screenshot();- await expect(screenshot1).toMatchSnapshot(filename1, { maxDiffPixels: 30 });+ await expect(screenshot1).toMatchSnapshot(filename1, { maxDiffPixels: 100 });// restore the hidden rowawait page.evaluate(async () => {@@ -159,7 +159,7 @@ test('diff formula related', async () => {const filename2 = generateSnapshotName('formula-filter-row-current-worksheet');const screenshot2 = await page.locator(SHEET_MAIN_CANVAS_ID).screenshot();- await expect(screenshot2).toMatchSnapshot(filename2, { maxDiffPixels: 30 });+ await expect(screenshot2).toMatchSnapshot(filename2, { maxDiffPixels: 100 });await page.evaluate(async () => {const worksheet2 = window.univerAPI.getActiveWorkbook().getSheetByName('formula2');@@ -170,7 +170,7 @@ test('diff formula related', async () => {const filename3 = generateSnapshotName('formula-filter-row-other-worksheet');const screenshot3 = await page.locator(SHEET_MAIN_CANVAS_ID).screenshot();- await expect(screenshot3).toMatchSnapshot(filename3, { maxDiffPixels: 30 });+ await expect(screenshot3).toMatchSnapshot(filename3, { maxDiffPixels: 100 });await page.waitForTimeout(1000);await browser.close();diff --git a/examples/src/sheets/custom-plugin/import-csv-button.ts b/examples/src/sheets/custom-plugin/import-csv-button.tsnew file mode 100644index 0000000000..45297c3514--- /dev/null+++ b/examples/src/sheets/custom-plugin/import-csv-button.ts@@ -0,0 +1,225 @@+/**+ * 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 { ICommand, IMutationInfo, Workbook } from '@univerjs/core';+import type { ISetRangeValuesMutationParams, ISetWorksheetColumnCountMutationParams, ISetWorksheetRowCountMutationParams } from '@univerjs/sheets';+import {+ CommandType,+ ICommandService,+ Inject,+ Injector,+ IUndoRedoService,+ IUniverInstanceService,+ Plugin,+ sequenceExecute,+ UniverInstanceType,+} from '@univerjs/core';+import { FolderSingle } from '@univerjs/icons';+import {+ SetRangeValuesMutation,+ SetRangeValuesUndoMutationFactory,+ SetWorksheetColumnCountMutation,+ SetWorksheetColumnCountUndoMutationFactory,+ SetWorksheetRowCountMutation,+ SetWorksheetRowCountUndoMutationFactory,+} from '@univerjs/sheets';+import { covertCellValues } from '@univerjs/sheets/facade';+import {+ ComponentManager,+ IMenuManagerService,+ MenuItemType,+ RibbonStartGroup,+} from '@univerjs/ui';++/**+ * wait user select csv file+ */+function waitUserSelectCSVFile(onSelect: (data: {+ data: string[][];+ colsCount: number;+ rowsCount: number;+}) => boolean): Promise<boolean> {+ return new Promise((resolve) => {+ const input = document.createElement('input');+ input.type = 'file';+ input.accept = '.csv';+ input.click();++ input.onchange = () => {+ const file = input.files?.[0];+ if (!file) return;+ const reader = new FileReader();+ reader.onload = () => {+ const text = reader.result;+ if (typeof text !== 'string') return;++ // tip: use npm package to parse csv+ const rows = text.split(/\r\n|\n/);+ const data = rows.map((line) => line.split(','));++ const colsCount = data.reduce((max, row) => Math.max(max, row.length), 0);++ const result = onSelect({+ data,+ colsCount,+ rowsCount: data.length,+ });++ resolve(result);+ };+ reader.readAsText(file);+ };+ });+}++/**+ * Import CSV Button Plugin+ * A simple Plugin example, show how to write a plugin.+ */+class ImportCSVButtonPlugin extends Plugin {+ static override pluginName = 'import-csv-plugin';++ constructor(+ _config: null,+ // inject injector, required+ @Inject(Injector) readonly _injector: Injector,+ // inject menu service, to add toolbar button+ @Inject(IMenuManagerService) private readonly menuManagerService: IMenuManagerService,+ // inject command service, to register command handler+ @Inject(ICommandService) private readonly commandService: ICommandService,+ // inject component manager, to register icon component+ @Inject(ComponentManager) private readonly componentManager: ComponentManager+ ) {+ super();+ }++ /**+ * The first lifecycle of the plugin mounted on the Univer instance,+ * the Univer business instance has not been created at this time.+ * The plugin should add its own module to the dependency injection system at this lifecycle.+ * It is not recommended to initialize the internal module of the plugin outside this lifecycle.+ */+ override onStarting() {+ // register icon component+ this.componentManager.register('FolderSingle', FolderSingle);++ const buttonId = 'import-csv-button';++ const command: ICommand = {+ type: CommandType.OPERATION,+ id: buttonId,+ handler: (accessor) => {+ // inject univer instance service+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const commandService = accessor.get(ICommandService);+ const undoRedoService = accessor.get(IUndoRedoService);++ // get current sheet+ const worksheet = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet();+ const unitId = worksheet.getUnitId();+ const subUnitId = worksheet.getSheetId();++ // wait user select csv file, then assemble multiple mutations operation to enable correct undo/redo+ return waitUserSelectCSVFile(({ data, rowsCount, colsCount }) => {+ const redoMutations: IMutationInfo[] = [];+ const undoMutations: IMutationInfo[] = [];++ // set sheet row count+ const setRowCountMutationRedoParams: ISetWorksheetRowCountMutationParams = {+ unitId,+ subUnitId,+ rowCount: rowsCount,+ };+ const setRowCountMutationUndoParams: ISetWorksheetRowCountMutationParams = SetWorksheetRowCountUndoMutationFactory(+ accessor,+ setRowCountMutationRedoParams+ );+ redoMutations.push({ id: SetWorksheetRowCountMutation.id, params: setRowCountMutationRedoParams });+ undoMutations.push({ id: SetWorksheetRowCountMutation.id, params: setRowCountMutationUndoParams });++ // set sheet column count+ const setColumnCountMutationRedoParams: ISetWorksheetColumnCountMutationParams = {+ unitId,+ subUnitId,+ columnCount: colsCount,+ };+ const setColumnCountMutationUndoParams: ISetWorksheetColumnCountMutationParams = SetWorksheetColumnCountUndoMutationFactory(+ accessor,+ setColumnCountMutationRedoParams+ );+ redoMutations.push({ id: SetWorksheetColumnCountMutation.id, params: setColumnCountMutationRedoParams });+ undoMutations.unshift({ id: SetWorksheetColumnCountMutation.id, params: setColumnCountMutationUndoParams });++ // parse csv to univer data+ const cellValue = covertCellValues(data, {+ startColumn: 0, // start column index+ startRow: 0, // start row index+ endColumn: colsCount - 1, // end column index+ endRow: rowsCount - 1, // end row index+ });++ // set sheet data+ const setRangeValuesMutationRedoParams: ISetRangeValuesMutationParams = {+ unitId,+ subUnitId,+ cellValue,+ };+ const setRangeValuesMutationUndoParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(+ accessor,+ setRangeValuesMutationRedoParams+ );+ redoMutations.push({ id: SetRangeValuesMutation.id, params: setRangeValuesMutationRedoParams });+ undoMutations.unshift({ id: SetRangeValuesMutation.id, params: setRangeValuesMutationUndoParams });++ const result = sequenceExecute(redoMutations, commandService);++ if (result.result) {+ undoRedoService.pushUndoRedo({+ unitID: unitId,+ undoMutations,+ redoMutations,+ });++ return true;+ }++ return false;+ });+ },+ };++ const menuItemFactory = () => ({+ id: buttonId,+ title: 'Import CSV',+ tooltip: 'Import CSV',+ icon: 'FolderSingle', // icon name+ type: MenuItemType.BUTTON,+ });++ this.menuManagerService.mergeMenu({+ [RibbonStartGroup.OTHERS]: {+ [buttonId]: {+ order: 10,+ menuItemFactory,+ },+ },+ });++ this.commandService.registerCommand(command);+ }+}++export default ImportCSVButtonPlugin;diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.tsindex 8068cca3ac..c3631375bc 100644--- a/examples/src/sheets/main.ts+++ b/examples/src/sheets/main.ts@@ -50,6 +50,8 @@ import { UniverUIPlugin } from '@univerjs/ui';import { enUS, faIR, frFR, ruRU, viVN, zhCN, zhTW } from '../locales';import { UniverSheetsCustomMenuPlugin } from './custom-menu';+import ImportCSVButtonPlugin from './custom-plugin/import-csv-button';+import '@univerjs/sheets/facade';import '@univerjs/ui/facade';import '@univerjs/docs-ui/facade';@@ -144,6 +146,8 @@ function createNewInstance() {univer.registerPlugin(UniverSheetTableUIPlugin);univer.registerPlugin(UniverNetworkPlugin);+ univer.registerPlugin(ImportCSVButtonPlugin);+// If we are running in e2e platform, we should immediately register the debugger plugin.if (IS_E2E) {univer.registerPlugin(UniverDebuggerPlugin, {diff --git a/packages/sheets/src/commands/commands/set-worksheet-column-count.command.ts b/packages/sheets/src/commands/commands/set-worksheet-column-count.command.tsindex de47b2d82b..b90d700e5f 100644--- a/packages/sheets/src/commands/commands/set-worksheet-column-count.command.ts+++ b/packages/sheets/src/commands/commands/set-worksheet-column-count.command.ts@@ -22,7 +22,7 @@ import {IUndoRedoService,IUniverInstanceService,} from '@univerjs/core';-import { SetWorksheetColumnCountMutation, SetWorksheetColumnCountMutationFactory } from '../mutations/set-worksheet-column-count.mutation';+import { SetWorksheetColumnCountMutation, SetWorksheetColumnCountUndoMutationFactory } from '../mutations/set-worksheet-column-count.mutation';import { getSheetCommandTarget } from './utils/target-util';export const SetWorksheetColumnCountCommand: ICommand = {@@ -45,7 +45,7 @@ export const SetWorksheetColumnCountCommand: ICommand = {columnCount,};- const undoMutationParams = SetWorksheetColumnCountMutationFactory(accessor, redoMutationParams);+ const undoMutationParams = SetWorksheetColumnCountUndoMutationFactory(accessor, redoMutationParams);const result = commandService.syncExecuteCommand(SetWorksheetColumnCountMutation.id, redoMutationParams);diff --git a/packages/sheets/src/commands/commands/set-worksheet-row-count.command.ts b/packages/sheets/src/commands/commands/set-worksheet-row-count.command.tsindex 9ed07600f6..14ee9dd02a 100644--- a/packages/sheets/src/commands/commands/set-worksheet-row-count.command.ts+++ b/packages/sheets/src/commands/commands/set-worksheet-row-count.command.ts@@ -22,7 +22,7 @@ import {IUndoRedoService,IUniverInstanceService,} from '@univerjs/core';-import { SetWorksheetRowCountMutation, SetWorksheetRowCountMutationFactory } from '../mutations/set-worksheet-row-count.mutation';+import { SetWorksheetRowCountMutation, SetWorksheetRowCountUndoMutationFactory } from '../mutations/set-worksheet-row-count.mutation';import { getSheetCommandTarget } from './utils/target-util';export const SetWorksheetRowCountCommand: ICommand = {@@ -45,7 +45,7 @@ export const SetWorksheetRowCountCommand: ICommand = {rowCount,};- const undoMutationParams = SetWorksheetRowCountMutationFactory(accessor, redoMutationParams);+ const undoMutationParams = SetWorksheetRowCountUndoMutationFactory(accessor, redoMutationParams);const result = commandService.syncExecuteCommand(SetWorksheetRowCountMutation.id, redoMutationParams);diff --git a/packages/sheets/src/commands/mutations/set-worksheet-column-count.mutation.ts b/packages/sheets/src/commands/mutations/set-worksheet-column-count.mutation.tsindex 399b2ffa1c..0f9dde2b11 100644--- a/packages/sheets/src/commands/mutations/set-worksheet-column-count.mutation.ts+++ b/packages/sheets/src/commands/mutations/set-worksheet-column-count.mutation.ts@@ -24,13 +24,13 @@ export interface ISetWorksheetColumnCountMutationParams {columnCount: number;}-export const SetWorksheetColumnCountMutationFactory = (+export const SetWorksheetColumnCountUndoMutationFactory = (accessor: IAccessor,params: ISetWorksheetColumnCountMutationParams): ISetWorksheetColumnCountMutationParams => {const target = getSheetMutationTarget(accessor.get(IUniverInstanceService), params);if (!target) {- throw new Error('[SetWorksheetColumnCountMutationFactory]: worksheet is null error!');+ throw new Error('[SetWorksheetColumnCountUndoMutationFactory]: worksheet is null error!');}return {diff --git a/packages/sheets/src/commands/mutations/set-worksheet-row-count.mutation.ts b/packages/sheets/src/commands/mutations/set-worksheet-row-count.mutation.tsindex a01b47d574..c79d74324a 100644--- a/packages/sheets/src/commands/mutations/set-worksheet-row-count.mutation.ts+++ b/packages/sheets/src/commands/mutations/set-worksheet-row-count.mutation.ts@@ -24,13 +24,13 @@ export interface ISetWorksheetRowCountMutationParams {rowCount: number;}-export const SetWorksheetRowCountMutationFactory = (+export const SetWorksheetRowCountUndoMutationFactory = (accessor: IAccessor,params: ISetWorksheetRowCountMutationParams): ISetWorksheetRowCountMutationParams => {const target = getSheetMutationTarget(accessor.get(IUniverInstanceService), params);if (!target) {- throw new Error('[SetWorksheetRowCountMutationFactory]: worksheet is null error!');+ throw new Error('[SetWorksheetRowCountUndoMutationFactory]: worksheet is null error!');}return {diff --git a/packages/sheets/src/facade/index.ts b/packages/sheets/src/facade/index.tsindex ef874f072d..cdc26b0c86 100644--- a/packages/sheets/src/facade/index.ts+++ b/packages/sheets/src/facade/index.ts@@ -28,3 +28,4 @@ export { FWorkbook } from './f-workbook';// eslint-disable-next-line perfectionist/sort-exportsexport type * from './f-univer';export { FWorksheet } from './f-worksheet';+export { covertCellValues } from './utils';diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.tsindex 1dd3782bc9..d0685e856e 100644--- a/packages/sheets/src/index.ts+++ b/packages/sheets/src/index.ts@@ -464,7 +464,7 @@ export { SheetSkeletonService } from './skeleton/skeleton.service';export { SetWorksheetRowCountCommand } from './commands/commands/set-worksheet-row-count.command';export { SetWorksheetColumnCountCommand } from './commands/commands/set-worksheet-column-count.command';-export { type ISetWorksheetRowCountMutationParams, SetWorksheetRowCountMutation } from './commands/mutations/set-worksheet-row-count.mutation';-export { type ISetWorksheetColumnCountMutationParams, SetWorksheetColumnCountMutation } from './commands/mutations/set-worksheet-column-count.mutation';+export { type ISetWorksheetRowCountMutationParams, SetWorksheetRowCountMutation, SetWorksheetRowCountUndoMutationFactory } from './commands/mutations/set-worksheet-row-count.mutation';+export { type ISetWorksheetColumnCountMutationParams, SetWorksheetColumnCountMutation, SetWorksheetColumnCountUndoMutationFactory } from './commands/mutations/set-worksheet-column-count.mutation';// #endregion