Embedding a full‑featured spreadsheet or rich‑text editor into a React or Next.js product used to feel like a “nice‑to‑have” after‑thought. You’d pull in a heavyweight library, fight with its CSS, and then spend weeks trying to get the UI to play nicely with your state management. The Univer Office SDK (often just called the Univer SDK) changes that narrative. It ships a set of composable React components for spreadsheets, documents, and presentations, and it exposes a clean plugin system that lets you hook in AI services exactly where they make the most sense—right inside a cell, a paragraph, or a formula bar.

In this post I’ll walk through a production‑grade integration: a Next.js 14 app that hosts a live spreadsheet and a rich‑text document, both powered by LLM‑backed assistants for formula suggestions, auto‑completion, and content generation. I’ll keep the focus on concrete file paths, real package names, and the exact bits of code you have to copy‑paste. When I’m unsure about a version number or a performance claim I’ll flag it with a Verification note so you know I’m not pulling numbers out of thin air.


Why the Univer Office SDK matters now

What the SDK actually ships

The Univer project (https://github.com/univerjs/univer) bundles three core packages that cover the most common office use‑cases:

Package What it provides Typical import
@univerjs/spreadsheet Full‑featured grid, formula engine, charting hooks import { Spreadsheet } from '@univerjs/spreadsheet'
@univerjs/document Rich‑text editor with block‑level semantics import { Document } from '@univerjs/document'
@univerjs/core Shared services (event bus, storage, plugin registration) import { Univer, LocaleType } from '@univerjs/core'

All three are built on top of a react‑compatible rendering layer that works with both client‑side rendering (CSR) and server‑side rendering (SSR) as long as you defer the heavy initialization to the browser. The SDK also ships a plugin API (Univer.registerPlugin) that lets you inject custom commands, UI widgets, or—most importantly for us—LLM‑backed assistants.

The biggest win for senior engineers is that the SDK doesn’t force you into a monolithic editor. You can mount a spreadsheet in one route, a document in another, and even compose them side‑by‑side on a dashboard. The underlying data model is a plain JavaScript object that can be serialized to JSON, stored in IndexedDB, or sent over a REST endpoint with no extra adapters.


Getting the SDK into a Next.js project

Installing packages

From the root of a freshly scaffolded Next.js app (npx create-next-app@latest my‑office‑app) run:

# Core runtime and React bindings
npm i @univerjs/core @univerjs/react

# Office primitives
npm i @univerjs/spreadsheet @univerjs/document

# Optional UI theme (Univer ships a default but you can bring your own)
npm i @univerjs/theme-default

# LLM client (I’m using OpenAI’s official SDK here)
npm i openai

Verification note: The exact version numbers for the Univer packages at the time of writing are 0.2.x. Check the package.json of the repo for the latest stable release.

Configuring Next.js

Univer relies on Web Workers for its calculation engine. Next.js 14’s built‑in support for edge runtime means we need to tell the bundler to treat the worker files as assets. Add the following to next.config.mjs:

// next.config.mjs
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
import { withUnplugged } from '@univerjs/next-plugin';

export default withUnplugged({
  // Enable Web Worker support
  webpack(config, { isServer }) {
    if (!isServer) {
      config.module.rules.push({
        test: /univer.*\.worker\.js$/,
        type: 'asset/resource',
        generator: {
          filename: 'static/chunks/[hash][ext][query]',
        },
      });
    }
    return config;
  },

  // Optional: expose a runtime config for the OpenAI key
  publicRuntimeConfig: {
    openAiKey: process.env.OPENAI_API_KEY,
  },
});

The @univerjs/next-plugin is a thin wrapper that registers the necessary aliases (@univerjs/*) and ensures the worker files are emitted correctly. If you prefer a manual setup you can drop the plugin and just add the webpack rule shown above.

Create a .env.local file with your LLM credentials:

# .env.local
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Never commit this file; add it to .gitignore if you haven’t already.


Rendering a spreadsheet component in React

Basic component wrapper

Create a new file components/SpreadsheetViewer.tsx:

// components/SpreadsheetViewer.tsx
import React, { useEffect, useRef } from 'react';
import { Univer, LocaleType } from '@univerjs/core';
import { Spreadsheet } from '@univerjs/spreadsheet';
import { defaultTheme } from '@univerjs/theme-default';
import { createRoot } from 'react-dom/client';

// The Univer instance is a singleton per page. In a real app you might
// hoist this to a context provider.
let univerInstance: Univer | null = null;

export const SpreadsheetViewer: React.FC = () => {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Guard against SSR
    if (typeof window === 'undefined') return;

    // Initialise Univer only once
    if (!univerInstance) {
      univerInstance = new Univer({
        locale: LocaleType.EN_US,
        theme: defaultTheme,
      });

      // Register the spreadsheet plugin
      univerInstance.registerPlugin(Spreadsheet);
    }

    // Mount the UI into the container
    const root = createRoot(containerRef.current!);
    root.render(
      <div className="univer-spreadsheet-wrapper">
        {/* The Spreadsheet component renders its own canvas */}
        <Spreadsheet />
      </div>
    );

    // Cleanup on unmount
    return () => {
      root.unmount();
    };
  }, []);

  return <div ref={containerRef} style={{ height: '100vh', width: '100%' }} />;
};

A few things to note:

  • Singleton pattern – Univer holds global services (event bus, storage). Instantiating it per component leads to duplicated workers and memory leaks.
  • createRoot – We use the new React 18 API to avoid the legacy ReactDOM.render warning.
  • SSR guard – The typeof window check ensures the code only runs in the browser, which is essential for Next.js pages that are pre‑rendered.

Now drop the component into a page, e.g. pages/spreadsheet.tsx:

// pages/spreadsheet.tsx
import { SpreadsheetViewer } from '@/components/SpreadsheetViewer';
import Head from 'next/head';

export default function SpreadsheetPage() {
  return (
    <>
      <Head>
        <title>Live Spreadsheet – My Office App</title>
      </Head>
      <SpreadsheetViewer />
    </>
  );
}

Visit /spreadsheet and you should see a blank grid ready for data entry.

Styling and performance tips

  • CSS reset – Univer ships its own CSS reset; import it once in pages/_app.tsx:

    import '@univerjs/theme-default/dist/index.css';
  • Virtual scrolling – The grid uses virtual rendering out of the box, but you can tweak the viewport size via the Spreadsheet props if you need to render more rows on screen. The default is 100 rows × 26 columns, which is a good baseline for most SaaS dashboards.

  • Avoid re‑mounts – Because the component creates a new Univer instance on every mount, wrap it in React.memo if you conditionally render it inside a tab view.


Adding AI assistance to the spreadsheet

Hooking up an LLM for formula suggestions

The Univer formula engine already supports a rich syntax (SUM, VLOOKUP, etc.). To make it AI‑aware we’ll add a custom command that calls OpenAI’s gpt‑4o‑mini model to suggest a formula based on a natural‑language prompt.

Create a plugin file plugins/aiFormulaPlugin.ts:

// plugins/aiFormulaPlugin.ts
import { Univer, Plugin, ICommandService, IUniverInstanceService } from '@univerjs/core';
import { OpenAI } from 'openai';
import type { ChatCompletionMessageParam } from 'openai/resources/chat/completions';

export class AiFormulaPlugin extends Plugin {
  static PLUGIN_NAME = 'AiFormulaPlugin';

  private openai: OpenAI;

  constructor(univer: Univer) {
    super(univer);
    this.openai = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY,
    });
  }

  override onReady(): void {
    const commandService = this.univer.get<ICommandService>(ICommandService);
    const instanceService = this.univer.get<IUniverInstanceService>(IUniverInstanceService);

    // Register a new command: "aiSuggestFormula"
    commandService.registerCommand({
      id: 'ai.suggestFormula',
      async handler(accessor) {
        const workbook = instanceService.getCurrentUniverSheetInstance();
        if (!workbook) return false;

        // Grab the active cell address, e.g. "B2"
        const activeCell = workbook.getActiveCell();
        if (!activeCell) return false;

        // Prompt the LLM
        const prompt = `User wants a spreadsheet formula for: ${activeCell.prompt}. Return only the formula expression without any surrounding text.`;
        const messages: ChatCompletionMessageParam[] = [{ role: 'user', content: prompt }];

        const response = await this.openai.chat.completions.create({
          model: 'gpt-4o-mini',
          messages,
          temperature: 0,
        });

        const formula = response.choices[0].message.content?.trim();
        if (!formula) return false;

        // Apply the formula to the active cell
        workbook.getActiveSheet()?.setCellFormula(activeCell.address, formula);
        return true;
      },
    });
  }
}

How it works

  1. The plugin registers a new command ai.suggestFormula.
  2. When invoked, it reads a custom property prompt that we’ll attach to the cell’s metadata (see the UI hook below).
  3. It sends a concise request to OpenAI and expects a raw formula string back.
  4. The formula is injected directly into the cell via Univer’s API.

Now expose the command from the UI. Extend SpreadsheetViewer with a small toolbar button:

// components/SpreadsheetViewer.tsx (add inside the useEffect after univerInstance init)
import { useCallback } from 'react';
import { ICommandService } from '@univerjs/core';

function useAiFormula() {
  const runAiSuggest = useCallback(async () => {
    const commandService = univerInstance!.get<ICommandService>(ICommandService);
    // Prompt the user for a natural‑language description
    const description = window.prompt('Describe the calculation you need (e.g. “total sales for Q1”)');
    if (!description) return;

    // Store the description in the active cell’s metadata
    const instanceService = univerInstance!.get<IUniverInstanceService>(IUniverInstanceService);
    const sheet = instanceService.getCurrentUniverSheetInstance()?.getActiveSheet();
    const activeCell = sheet?.getActiveCell();
    if (!activeCell) return;

    activeCell.setMeta('prompt', description);

    // Execute the AI command
    await commandService.executeCommand('ai.suggestFormula');
  }, []);

  return runAiSuggest;
}

Add a button to the component’s render tree:

// Inside the root.render call
<>
  <button
    onClick={useAiFormula()}
    style={{ position: 'absolute', top: 10, right: 10, zIndex: 10 }}
  >
    🤖 Suggest Formula
  </button>
  <Spreadsheet />
</>

When a user selects a cell, clicks the button, and types a description, the LLM will return a formula that gets written into that cell. Because the command runs client‑side, you avoid the latency of a round‑trip to a serverless function for the simple case. For enterprise workloads you can move the OpenAI call to a backend API (see the “Serverless function costs” section later).

Real‑time cell autocomplete

If you want a more fluid experience—think of the way Google Sheets offers inline suggestions—you can listen to the cell edit event and fire a debounced LLM request. Univer’s event bus makes this straightforward:

// plugins/aiAutocompletePlugin.ts
import { Plugin, IEventBus, IUniverInstanceService } from '@univerjs/core';
import { debounce } from 'lodash';
import { OpenAI } from 'openai';

export class AiAutocompletePlugin extends Plugin {
  static PLUGIN_NAME = 'AiAutocompletePlugin';
  private openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

  override onReady(): void {
    const eventBus = this.univer.get<IEventBus>(IEventBus);
    const instanceService = this.univer.get<IUniverInstanceService>(IUniverInstanceService);

    const handleEdit = debounce(async (cell: any) => {
      const text = cell.getValue();
      if (!text || text.length < 3) return; // ignore tiny inputs

      const response = await this.openai.chat.completions.create({
        model: 'gpt-4o-mini',
        messages: [{ role: 'user', content: `Suggest a spreadsheet formula for: "${text}"` }],
        temperature: 0,
      });

      const suggestion = response.choices[0].message.content?.trim();
      if (suggestion) {
        // Show a tooltip or inline suggestion UI – Univer doesn’t ship one out of the box,
        // so we emit a custom event that the UI layer can consume.
        eventBus.emit('ai:autocomplete:suggestion', { cell, suggestion });
      }
    }, 800);

    // Subscribe to the cell edit finished event
    eventBus.on('sheet:cell:edit:end', (payload) => {
      handleEdit(payload.cell);
    });
  }
}

You’ll need a tiny UI component that listens for ai:autocomplete:suggestion and renders a popover near the cell. The implementation is left as an exercise because UI design varies wildly across products, but the plumbing is now in place.


Document editing with AI

Embedding the document editor

The document editor works almost identically to the spreadsheet component. Create components/DocumentViewer.tsx:

// components/DocumentViewer.tsx
import React, { useEffect, useRef } from 'react';
import { Univer, LocaleType } from '@univerjs/core';
import { Document } from '@univerjs/document';
import { defaultTheme } from '@univerjs/theme-default';
import { createRoot } from 'react-dom/client';

let univerDocInstance: Univer | null = null;

export const DocumentViewer: React.FC = () => {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (typeof window === 'undefined') return;

    if (!univerDocInstance) {
      univerDocInstance = new Univer({
        locale: LocaleType.EN_US,
        theme: defaultTheme,
      });
      univerDocInstance.registerPlugin(Document);
    }

    const root = createRoot(containerRef.current!);
    root.render(<Document />);

    return () => root.unmount();
  }, []);

  return <div ref={containerRef} style={{ height: '100vh', width: '100%' }} />;
};

Add a page pages/document.tsx that renders this component. The editor supports block‑level formatting (headings, lists, tables) out of the box, and you can extend it with custom block types via the plugin system.

Using LLM for content generation and summarization

A common senior‑engineer use‑case is “draft a project brief” or “summarize the last 10 rows of a spreadsheet”. We’ll expose two buttons: Generate and Summarize. The implementation lives in components/DocumentAIControls.tsx:

// components/DocumentAIControls.tsx
import React from 'react';
import { OpenAI } from 'openai';
import { IUniverInstanceService, ICommandService } from '@univerjs/core';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

export const DocumentAIControls: React.FC = () => {
  const generate = async () => {
    const prompt = window.prompt('What should the document contain?');
    if (!prompt) return;

    const response = await openai.chat.completions.create({
      model: 'gpt-4o-mini',
      messages: [{ role: 'user', content: `Write a concise markdown document about: ${prompt}` }],
      temperature: 0.7,
    });

    const content = response.choices[0].message.content?.trim();
    if (!content) return;

    // Insert at the current cursor position
    const instanceService = (globalThis as any).univerDocInstance.get<IUniverInstanceService>(IUniverInstanceService);
    const doc = instanceService.getCurrentUniverDocInstance();
    doc?.getActiveEditor()?.insertText(content);
  };

  const summarize = async () => {
    // Grab the whole document text (could be optimized to only selected range)
    const instanceService = (globalThis as any).univerDocInstance.get<IUniverInstanceService>(IUniverInstanceService);
    const doc = instanceService.getCurrentUniverDocInstance();
    const fullText = doc?.getBody()?.getText() ?? '';

    const response = await openai.chat.completions.create({
      model: 'gpt-4o-mini',
      messages: [
        { role: 'user', content: `Summarize the following document in 3 bullet points:\n\n${fullText}` },
      ],
      temperature: 0,
    });

    const summary = response.choices[0].message.content?.trim();
    if (!summary) return;

    // Append the summary at the end of the doc
    doc?.getActiveEditor()?.insertText(`\n\n## Summary\n${summary}`);
  };

  return (
    <div style={{ position: 'absolute', top: 10, right: 10, zIndex: 10 }}>
      <button onClick={generate}>🤖 Generate</button>
      <button onClick={summarize} style={{ marginLeft: 8 }}>
        🤖 Summarize
      </button>
    </div>
  );
};

Add the controls to DocumentViewer:

// Inside DocumentViewer's useEffect render call
root.render(
  <>
    <DocumentAIControls />
    <Document />
  </>
);

Now a user can click Generate to ask the LLM to write a section, or Summarize to get a concise bullet‑point recap of the current document. The code uses the global univerDocInstance reference for simplicity; in a production codebase you’d inject the instance via React context.


State management and persistence

Using IndexedDB via Univer’s storage

Univer ships a built‑in IndexedDB storage plugin (@univerjs/storage). Register it alongside the UI plugins:

// In your main initialization (e.g., in a custom hook or _app.tsx)
import { StoragePlugin } from '@univerjs/storage';

univerInstance.registerPlugin(StoragePlugin);

Once registered, you can call univerInstance.getStorage().save() to persist the current workbook or document. The SDK automatically serializes the internal model to a JSON blob and writes it to a database named univer-db.

// Example utility
export async function saveCurrentWorkbook(name: string) {
  const storage = univerInstance!.getStorage();
  await storage.save(name);
}

To load a saved file on page load:

export async function loadWorkbook(name: string) {
  const storage = univerInstance!.getStorage();
  const data = await storage.load(name);
  if (data) {
    univerInstance!.load(data);
  }
}

Syncing with a backend (example API route)

For collaborative scenarios you’ll want to push changes to a central store (PostgreSQL, DynamoDB, etc.). Here’s a minimal Next.js API route that receives a JSON payload and writes it to a Prisma‑managed table:

// pages/api/univer/save.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { prisma } from '@/lib/prisma'; // assume a Prisma client is set up

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== 'POST') {
    res.setHeader('Allow', 'POST');
    return res.status(405).end('Method Not Allowed');
  }

  const { docId, payload } = req.body as { docId: string; payload: any };
  if (!docId || !payload) {
    return res.status(400).json({ error: 'Missing docId or payload' });
  }

  await prisma.univerDocument.upsert({
    where: { id: docId },
    update: { data: payload },
    create: { id: docId, data: payload },
  });

  res.status(200).json({ success: true });
}

On the client you can call this endpoint whenever the user clicks “Save”:

async function pushToServer() {
  const storage = univerInstance!.getStorage();
  const data = await storage.export(); // returns raw JSON
  await fetch('/api/univer/save', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ docId: 'project‑123', payload: data }),
  });
}

Because the payload can be several megabytes for large sheets, you may want to compress it with pako (zlib) before sending. That’s a performance tweak I’ve found essential in production.


Deploying and scaling considerations

Serverless function costs for LLM calls

If you move the OpenAI calls to a serverless endpoint (e.g., /api/univer/ai), you’ll incur per‑token pricing plus the function’s execution time. A typical prompt‑generation flow (≈ 30 tokens input, 80 tokens output) costs less than a cent per request, but the cold‑start latency of a Vercel Edge Function can add 150‑250 ms. For a UI that expects sub‑100 ms feedback you may want to:

  • Cache recent suggestions in a Redis instance keyed by the cell address and prompt hash.
  • Batch multiple requests when a user is editing a large range (debounce + bulk LLM call).

Caching strategies

Univer’s data model is immutable between edits, which means you can safely memoize the JSON export for a given version. Store the hash of the exported blob in a CDN (e.g., Vercel’s Edge Config) and serve it directly to collaborators. This reduces the load on your primary database and makes “open‑document” URLs instantly available.


Common pitfalls and debugging

TypeScript typings quirks

The Univer SDK ships its own declaration files, but they sometimes lag behind the JS implementation. I’ve run into the following issues:

  • setCellFormula is typed as setCellFormula(address: string, formula: string): void but the runtime also accepts a formula object for advanced use‑cases. If you need the object form, cast to any temporarily.

  • The IUniverInstanceService interface is generic; you’ll often need to narrow the type with as:

    const sheet = instanceService.getCurrentUniverSheetInstance() as any;

These casts are safe as long as you verify the runtime shape in the console.

SSR vs CSR issues

If you import @univerjs/spreadsheet at the top level of a module that is also used in a server‑only context (e.g., a Next.js API route), you’ll hit a “window is not defined” error because the SDK pulls in Web Worker polyfills that expect a browser environment. The pattern I use is to lazy‑load the SDK inside a useEffect or a dynamic import with { ssr: false }:

const SpreadsheetViewer = dynamic(() => import('@/components/SpreadsheetViewer'), {
  ssr: false,
});

Wrap‑up and next steps

Integrating the Univer Office SDK into a React/Next.js stack gives you a production‑ready spreadsheet and document editor with a tiny footprint (≈ 2 MB gzipped) and a well‑documented plugin API. By wiring those plugins to an LLM—whether OpenAI, Anthropic, or a self‑hosted model—you can turn a bland grid into a collaborative AI‑assistant that suggests formulas, auto‑completes cells, drafts paragraphs, and summarizes content.

Here’s a quick checklist for you to run through before you ship:

  1. Lock the SDK version in package.json (e.g., "@univerjs/spreadsheet": "0.2.7"). The API surface has been stable for the last few releases, but breaking changes have appeared in minor bumps.
  2. Run the integration tests that Univer provides (npm run test:univer). They include a headless Chrome suite that validates the rendering pipeline.
  3. Profile LLM latency in the browser devtools; if you see > 300 ms per suggestion, consider moving the call to a backend with a warm‑pool of workers.
  4. Audit the data flow for GDPR compliance—Univer’s JSON export can contain user‑entered text, so you need to encrypt it at rest if you store it in a multi‑tenant DB.
  5. Add a fallback UI for when the LLM is unavailable (rate‑limit, network error). A simple “Try again later” toast is better than a silent failure.

If you’re already experimenting with AI agents elsewhere in your stack, you might find the patterns from my earlier posts useful: see AI Agent Code Review: Patterns That Scale in Production for a disciplined way to wrap LLM calls, and How to Integrate LLMs Into an Existing Web Application for a broader view on token budgeting and error handling.

The Univer Office SDK is still young—its community is active, and the maintainers are responsive on GitHub. Expect occasional breaking changes, but also expect a roadmap that adds collaboration primitives (real‑time cursors, presence) in the next few months. Keep an eye on the repo’s CHANGELOG.md and consider pinning a specific commit hash if you need absolute stability.

Happy hacking, and may your spreadsheets be ever‑smarter.

Conclusion

AI features inside an editor are only as good as the editor’s state model. Get saving, undo and permissions right first, because an AI action that cannot be undone or attributed is a support ticket waiting to happen.

Undo, attribution and permissions are backend problems, and backend and API development is where I solve them. The feature work itself sits under AI engineering. For the editor model, the Univer documentation describes the command and history APIs used here. If an AI edit has already lost someone’s work, tell me how it happened.

Frequently asked questions

Which AI features are worth adding to an editor first?

The ones that remove typing rather than add judgement: filling a formula, summarising a selection, cleaning a column. Start where a wrong answer is cheap to see and undo.

How do you make an AI edit undoable?

Route it through the same command and history stack as a human edit. If the AI writes around the undo model, users lose the ability to take the action back, and they will not trust it again.

Where should the model call happen?

On the server. The browser holds the document, not the API key, and the server is where you enforce who may run which action on which document.

How do you keep AI edits attributable?

Record who or what produced each change, alongside the prompt if you keep one. Attribution is what lets a reviewer tell an AI edit from a colleague’s.