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
fix(sheets): write Excel-compatible clipboard HTML (#7479)
wpxp12345604a7e8ee62a9
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.tsindex b6235738f6..3dfd2f693c 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts@@ -28,6 +28,7 @@ import {IUndoRedoService,IUniverInstanceService,LocaleService,+ LocaleType,LocalUndoRedoService,ObjectMatrix,RANGE_TYPE,@@ -143,8 +144,8 @@ interface IPrivateClipboardServiceAccess {_topLeftCellsMatch(rowCount: number, colCount: number, range: { topRow: number; leftCol: number }): boolean;}-function createTestContext() {- vi.stubGlobal('navigator', { appVersion: 'Linux' });+function createTestContext(appVersion = 'Linux') {+ vi.stubGlobal('navigator', { appVersion });const injector = new Injector();injector.add([ILogService, { useClass: DesktopLogService }]);injector.add([IConfigService, { useClass: ConfigService }]);@@ -163,6 +164,10 @@ function createTestContext() {injector.add([LocaleService]);injector.add([ErrorService]);injector.add([ISheetClipboardService, { useClass: SheetClipboardService }]);+ const localeService = injector.get(LocaleService);+ localeService.load({ [LocaleType.ZH_CN]: {} });+ localeService.setLocale(LocaleType.ZH_CN);+ localeService.setDirection('ltr');const commandService = injector.get(ICommandService);commandService.registerCommand(SetSelectionsOperation);commandService.registerCommand(SetWorksheetActiveOperation);@@ -276,6 +281,58 @@ describe('SheetClipboardService', () => {expect(copyId && service.copyContentCache().get(copyId)?.copyType).toBe(COPY_TYPE.COPY);});+ it('wraps merged sheet html with Excel metadata only when writing to the system clipboard', async () => {+ const { injector, service } = createTestContext();+ selectRange(injector, 1, 1, 2, 2);+ service.addClipboardHook({+ id: 'merged-cell-html',+ onCopyCellStyle(_row: number, _column: number, rowSpan?: number, colSpan?: number) {+ return rowSpan || colSpan+ ? { rowspan: `${rowSpan || 1}`, colspan: `${colSpan || 1}` }+ : undefined;+ },+ } as never);++ const generatedHtml = service.generateCopyContent('unit-1', 'sheet-1', {+ startRow: 1,+ startColumn: 1,+ endRow: 2,+ endColumn: 2,+ })?.html;++ expect(generatedHtml).toMatch(/^<google-sheets-html-origin><table/);+ expect(await service.copy()).toBe(true);++ const clipboard = injector.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;+ const writtenHtml = clipboard.writes[0].html;++ expect(writtenHtml).toContain('xmlns:o="urn:schemas-microsoft-com:office:office"');+ expect(writtenHtml).toContain('xmlns:x="urn:schemas-microsoft-com:office:excel"');+ expect(writtenHtml).toContain('xmlns="http://www.w3.org/TR/REC-html40"');+ expect(writtenHtml).toContain('<meta name="ProgId" content="Excel.Sheet">');+ expect(writtenHtml).toContain('<meta name="Generator" content="Univer">');+ expect(writtenHtml).toContain('<!--StartFragment--><table');+ expect(writtenHtml).toContain('rowspan="2" colspan="2"');+ expect(writtenHtml).toContain('data-copy-id=');+ expect(writtenHtml).toContain('</table><!--EndFragment-->');+ });++ it('recognizes its Excel-compatible clipboard html as internal content on Windows', async () => {+ const { injector, service } = createTestContext('Windows');+ selectCell(injector);+ const notificationService = injector.get(INotificationService);+ const notificationSpy = vi.spyOn(notificationService, 'show');++ expect(await service.copy()).toBe(true);++ const clipboard = injector.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;+ const item = new MockClipboardItem({ 'text/html': clipboard.writes[0].html });++ await service.paste(item as unknown as ClipboardItem);++ expect(notificationSpy).not.toHaveBeenCalled();+ });+it('writes formula clipboard payload for copyable formula cells', async () => {const { injector, service } = createTestContext();selectRange(injector, 1, 2, 2, 3);@@ -338,6 +395,7 @@ describe('SheetClipboardService', () => {const copyId = clipboard.writes[0].html.match(/data-copy-id="([^"]+)"/)?.[1];expect(cut).toBe(true);+ expect(clipboard.writes[0].html).toContain('xmlns:x="urn:schemas-microsoft-com:office:excel"');expect(service.copyContentCache().get(copyId!)?.copyType).toBe(COPY_TYPE.CUT);});diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.tsindex 19a9eb3b04..4b9998b6f8 100644--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts@@ -142,6 +142,12 @@ const IMAGE_MIME_TO_EXTENSION = {export const FORMULA_CLIPBOARD_MIME_TYPE = 'web application/x-univer-sheets-formula';+function wrapHtmlForExcel(html: string): string {+ const table = html.match(/<table[\s\S]*<\/table>/)?.[0] ?? html;++ return `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="ProgId" content="Excel.Sheet"><meta name="Generator" content="Univer"></head><body><!--StartFragment-->${table}<!--EndFragment--></body></html>`;+}+interface IFormulaClipboardPayload {rowCount: number;columnCount: number;@@ -331,7 +337,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard// 4. write html and get plain text info the clipboard interfaceawait this._clipboardInterfaceService.write(plain,- html,+ wrapHtmlForExcel(html),formulaClipboardPayload ? { [FORMULA_CLIPBOARD_MIME_TYPE]: formulaClipboardPayload } : undefined);@@ -370,7 +376,9 @@ export class SheetClipboardService extends Disposable implements ISheetClipboardconst shouldUseHTMLPaste = imageIndex === -1 || !htmlContainsImage(html);if (html && shouldUseHTMLPaste) {// Firstly see if the html content is from Excel- if (this._platformService.isWindows && htmlIsFromExcel(html)) {+ const copyId = extractId(html);+ const isInternalCopy = Boolean(copyId && this._copyContentCache.get(copyId));+ if (this._platformService.isWindows && htmlIsFromExcel(html) && !isInternalCopy) {this._notificationService.show({type: 'warning',title: this._localeService.t<LocaleKey>('sheets-ui.clipboard.shortCutNotify.title'),diff --git a/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts b/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.tsindex 791281533b..e70fa3a8fe 100644--- a/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts+++ b/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts@@ -132,6 +132,38 @@ describe('BrowserClipboardService', () => {expect(document.body.lastElementChild?.textContent).not.toBe('rich');});+ it('should preserve Univer Excel metadata while sanitizing legacy html', async () => {+ vi.mocked(supportClipboardAPI).mockReturnValue(false);+ const { service } = createService();+ const clipboardData = {+ setData: vi.fn(),+ };++ vi.mocked(document.execCommand).mockImplementation(() => {+ const event = new Event('copy', { cancelable: true }) as ClipboardEvent;+ Object.defineProperty(event, 'clipboardData', {+ value: clipboardData,+ });+ document.dispatchEvent(event);+ return true;+ });++ await service.write(+ 'merged',+ '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="ProgId" content="Excel.Sheet"><meta name="Generator" content="Univer"><script>alert(1)</script></head><body><!--StartFragment--><table data-copy-id="copy-id"><tbody><tr><td rowspan="3" onclick="alert(1)">merged</td></tr></tbody></table><!--EndFragment--></body></html>'+ );++ const copiedHtml = clipboardData.setData.mock.calls.find(([type]) => type === 'text/html')?.[1];++ expect(copiedHtml).toContain('xmlns:x="urn:schemas-microsoft-com:office:excel"');+ expect(copiedHtml).toContain('<meta name="ProgId" content="Excel.Sheet">');+ expect(copiedHtml).toContain('<!--StartFragment--><table data-copy-id="copy-id">');+ expect(copiedHtml).toContain('<td rowspan="3">merged</td>');+ expect(copiedHtml).toContain('</table><!--EndFragment-->');+ expect(copiedHtml).not.toContain('<script');+ expect(copiedHtml).not.toContain('onclick');+ });+it('should sanitize html before legacy copy', async () => {vi.mocked(supportClipboardAPI).mockReturnValue(false);const { service } = createService();diff --git a/packages/ui/src/services/clipboard/clipboard-interface.service.ts b/packages/ui/src/services/clipboard/clipboard-interface.service.tsindex 069051f758..4efa98d7eb 100644--- a/packages/ui/src/services/clipboard/clipboard-interface.service.ts+++ b/packages/ui/src/services/clipboard/clipboard-interface.service.ts@@ -373,7 +373,16 @@ function sanitizeHtmlForClipboard(html: string): DocumentFragment {function serializeSanitizedHtmlForClipboard(html: string): string {const container = document.createElement('div');container.appendChild(sanitizeHtmlForClipboard(html));- return container.innerHTML;+ const sanitizedHtml = container.innerHTML;+ const isUniverExcelHtml = html.includes('xmlns:x="urn:schemas-microsoft-com:office:excel"')+ && html.includes('<meta name="ProgId" content="Excel.Sheet">')+ && html.includes('<meta name="Generator" content="Univer">');++ if (!isUniverExcelHtml) {+ return sanitizedHtml;+ }++ return `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="ProgId" content="Excel.Sheet"><meta name="Generator" content="Univer"></head><body><!--StartFragment-->${sanitizedHtml}<!--EndFragment--></body></html>`;}function sanitizeHtmlNode(node: Node): Node | null {