Skip to content

Build your personal knowledge base with Trilium Notes

fix(spreadsheet): drop the font family from cells pasted from Excel

Elian Doranbdbb0bd47dee
diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsx b/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsx
index d47be1724e..d72f207376 100644
--- a/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsx
+++ b/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsx
@@ -30,6 +30,7 @@ import { t } from "../../../services/i18n";
import { isMobile } from "../../../services/utils";
import { useColorScheme, useEffectiveReadOnly, useTriliumEvent, useTriliumEvents } from "../../react/hooks";
import { TypeWidgetProps } from "../type_widget";
+import useStripPastedFontFamily from "./clipboard";
import useSpreadsheetExport from "./export";
import { loadUniverLocale, UniverLocale } from "./locales";
import useClampEdgeNavigation from "./navigation";
@@ -96,6 +97,7 @@ function SpreadsheetEditor({ note, noteContext, readOnly, locale }: TypeWidgetPr
useReleaseFillShortcuts(apiRef);
useClampEdgeNavigation(apiRef);
useAnchorCellEditorOnScroll(apiRef);
+ useStripPastedFontFamily(apiRef);
useDarkMode(apiRef);
const spacedUpdate = usePersistence(note, noteContext, apiRef, containerRef);
useSpreadsheetExport(apiRef, note, noteContext, spacedUpdate);
diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/clipboard.spec.ts b/apps/client/src/widgets/type_widgets/spreadsheet/clipboard.spec.ts
new file mode 100644
index 0000000000..0c4a13727c
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/spreadsheet/clipboard.spec.ts
@@ -0,0 +1,39 @@
+import { ObjectMatrix } from "@univerjs/core";
+import type { ICellDataWithSpanInfo } from "@univerjs/sheets-ui";
+import { describe, expect, it } from "vitest";
+
+import { stripPastedFontFamilies } from "./clipboard";
+
+describe("stripPastedFontFamilies", () => {
+ it("removes the font family from cell styles and rich-text runs, keeping the rest", () => {
+ const matrix = new ObjectMatrix<ICellDataWithSpanInfo>();
+ matrix.setValue(0, 0, { v: "plain", s: { ff: "Aptos Narrow", fs: 11, bl: 1 } });
+ matrix.setValue(0, 1, {
+ v: "rich",
+ s: { ff: "Calibri" },
+ p: {
+ id: "d",
+ documentStyle: { textStyle: { ff: "Calibri", it: 1 } },
+ body: {
+ dataStream: "rich\r\n",
+ textRuns: [
+ { st: 0, ed: 2, ts: { ff: "Arial", bl: 1 } },
+ { st: 2, ed: 4, ts: { ff: "Arial" } }
+ ]
+ }
+ }
+ });
+ matrix.setValue(1, 0, { v: "unstyled" });
+ matrix.setValue(1, 1, { v: "style id", s: "styleId" });
+
+ stripPastedFontFamilies(matrix);
+
+ expect(matrix.getValue(0, 0)).toEqual({ v: "plain", s: { fs: 11, bl: 1 } });
+ const rich = matrix.getValue(0, 1);
+ expect(rich?.s).toEqual({});
+ expect(rich?.p?.documentStyle.textStyle).toEqual({ it: 1 });
+ expect(rich?.p?.body?.textRuns?.map((run) => run.ts)).toEqual([ { bl: 1 }, {} ]);
+ expect(matrix.getValue(1, 0)).toEqual({ v: "unstyled" });
+ expect(matrix.getValue(1, 1)).toEqual({ v: "style id", s: "styleId" });
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/clipboard.ts b/apps/client/src/widgets/type_widgets/spreadsheet/clipboard.ts
new file mode 100644
index 0000000000..fd414692e8
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/spreadsheet/clipboard.ts
@@ -0,0 +1,71 @@
+import type { Injector, ITextStyle, ObjectMatrix } from "@univerjs/core";
+import type { FUniver } from "@univerjs/presets";
+import { type ICellDataWithSpanInfo, ISheetClipboardService } from "@univerjs/sheets-ui";
+import { type MutableRef, useEffect } from "preact/hooks";
+
+const STRIP_FONT_FAMILY_HOOK_ID = "trilium.strip-pasted-font-family";
+
+/**
+ * Drops the font family from cells pasted from outside Univer, since the font picker is hidden
+ * and Excel and other sources put a `font-family` on every cell. A copy within Univer carries a
+ * `copyId` and keeps its fonts, which an imported .xlsx file can set.
+ *
+ * `SheetClipboardService` sorts hooks by ascending `priority` and hands every hook the same
+ * cell matrix, so this hook runs first and edits the matrix before the default paste hook
+ * turns it into mutations.
+ */
+export default function useStripPastedFontFamily(apiRef: MutableRef<FUniver | undefined>) {
+ useEffect(() => {
+ const univerAPI = apiRef.current;
+ if (!univerAPI) return;
+
+ let hook: { dispose(): void } | undefined;
+ const register = () => {
+ if (hook) return;
+ const injector = (univerAPI as unknown as { _injector: Injector })._injector;
+ hook = injector.get(ISheetClipboardService).addClipboardHook({
+ id: STRIP_FONT_FAMILY_HOOK_ID,
+ priority: Number.MIN_SAFE_INTEGER,
+ onPasteCells(_pasteFrom, _pasteTo, data, payload) {
+ if (!payload.copyId) {
+ stripPastedFontFamilies(data);
+ }
+ return { undos: [], redos: [] };
+ }
+ });
+ };
+
+ // `UniverSheetsUIPlugin` registers `ISheetClipboardService` once the first workbook
+ // starts the lifecycle, which can happen before or after this effect runs.
+ if (univerAPI.getCurrentLifecycleStage() >= univerAPI.Enum.LifecycleStages.Ready) {
+ register();
+ }
+ const lifecycle = univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, ({ stage }) => {
+ if (stage >= univerAPI.Enum.LifecycleStages.Ready) {
+ register();
+ }
+ });
+ return () => {
+ lifecycle.dispose();
+ hook?.dispose();
+ };
+ }, [ apiRef ]);
+}
+
+export function stripPastedFontFamilies(matrix: ObjectMatrix<ICellDataWithSpanInfo>) {
+ matrix.forValue((_row, _col, cell) => {
+ if (cell.s && typeof cell.s === "object") {
+ delete cell.s.ff;
+ }
+ deleteFontFamily(cell.p?.documentStyle?.textStyle);
+ for (const run of cell.p?.body?.textRuns ?? []) {
+ deleteFontFamily(run.ts);
+ }
+ });
+}
+
+function deleteFontFamily(style: ITextStyle | undefined) {
+ if (style) {
+ delete style.ff;
+ }
+}
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Spreadsheets.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Spreadsheets.html
index 164dd88052..b5c0e55b65 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Spreadsheets.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Spreadsheets.html
@@ -74,7 +74,10 @@
</ul>
</li>
</ul>
-<aside class="admonition important">
+<p>Cells pasted from Excel or another application keep their formatting except
+ for the font, so they use the spreadsheet's font like the rest of the cells.</p>
+<aside
+class="admonition important">
<p>Import &amp; export for both .xlsx and .csv files are supported on a best-effort
basis. It does not support advanced features (data validation, scripting,
etc.). If you notice a particular issue, it can be <a href="#root/_help_wy8So3yZZlH9">reported</a>,
diff --git a/docs/User Guide/User Guide/Note Types/Spreadsheets.md b/docs/User Guide/User Guide/Note Types/Spreadsheets.md
index 755cefe9da..16237c7437 100644
--- a/docs/User Guide/User Guide/Note Types/Spreadsheets.md
+++ b/docs/User Guide/User Guide/Note Types/Spreadsheets.md
@@ -37,6 +37,8 @@ Both [import and export](../Basic%20Concepts%20and%20Features/Import%20%26%20Exp
* If exported as a single file via <a class="reference-link" href="../Basic%20Concepts%20and%20Features/Import%20%26%20Export.md">Import &amp; Export</a>, the resulting file will be a custom `.triliumsheet` file that preserves the spreadsheet as-is.
* The export is intentionally a different process than the normal <a class="reference-link" href="../Basic%20Concepts%20and%20Features/Import%20%26%20Export.md">Import &amp; Export</a> functionality because it does conversion to multiple formats with varying degrees of compatibility.
+Cells pasted from Excel or another application keep their formatting except for the font, so they use the spreadsheet's font like the rest of the cells.
+
> [!IMPORTANT]
> Import & export for both .xlsx and .csv files are supported on a best-effort basis. It does not support advanced features (data validation, scripting, etc.). If you notice a particular issue, it can be [reported](../Troubleshooting/Reporting%20issues.md), however all bug reports must contain a sample file in order to be taken into consideration.