@jitword/sheet-sdk

A self-contained spreadsheet SDK wrapping the Univer.js engine. Provides structured APIs for cell data manipulation, sheet management, Excel import/export, permissions, and real-time collaboration.

一个封装了 Univer.js 引擎的独立电子表格 SDK。提供单元格数据操作、工作表管理、Excel 导入导出、权限控制和实时协作等结构化 API。

Installation (CDN)

安装(CDN)

Load the SDK via <script> tags. The full bundle includes all dependencies (Univer engine, ExcelJS, etc.) in a single file.

通过 <script> 标签加载 SDK。完整包将所有依赖(Univer 引擎、ExcelJS 等)打包为单一文件。

<!-- 1. Univer CSS -->
<link rel="stylesheet" href="./lib/univer.css" />

<!-- 2. Process polyfill (required for bundled Node.js deps) -->
<script>
  if (typeof window.process === 'undefined') {
    window.process = {
      env: { NODE_ENV: 'production' },
      versions: { node: '' },
      nextTick: function(fn) { setTimeout(fn, 0) },
      browser: true
    };
  }
</script>

<!-- 3. JitSheet SDK (full bundle, UMD) -->
<script src="./lib/jit-sheet.full.js"></script>

Quick Start

快速开始

// Access the constructor from UMD global
// 从 UMD 全局变量获取构造函数
var JitSheet = window.JitSheet.JitSheet

// 1. Create instance | 创建实例
var sheet = new JitSheet({
  container: '#spreadsheet',
  locale: 'zh-CN',
  editable: true,
  onChange: function(snapshot) {
    console.log('Data changed', snapshot)
  }
})

// 2. Use sub-APIs | 使用子 API
sheet.data.setCellValue('sheet1', 0, 0, 'Hello')
sheet.sheets.createSheet('New Sheet')
sheet.io.exportExcel('report.xlsx')

// 3. Listen to events | 监听事件
sheet.on('change', function(snapshot) {
  console.log('Data changed', snapshot)
})

// 4. Cleanup | 销毁
sheet.destroy()

Configuration Options

配置选项

OptionTypeDefaultDescription
containerstring | HTMLElementRequired. CSS selector or DOM element.
locale'zh-CN' | 'en-US''zh-CN'UI locale for Univer.
editablebooleantrueAllow editing.
dataSheetSnapshot | nullnullInitial workbook data to load.
serverUrlstringREST API base URL for save/load.
wsUrlstringWebSocket URL for collaboration.
tokenstringJWT authentication token.
userIdstringCurrent user ID.
usernamestringCurrent user display name.
overridesArray[]Univer DI overrides for custom services.
onChangeFunctionCallback on data change.
onSaveFunctionCallback on save.
onErrorFunctionError handler callback.
选项类型默认值说明
containerstring | HTMLElement必填。 CSS 选择器或 DOM 元素。
locale'zh-CN' | 'en-US''zh-CN'Univer UI 语言。
editablebooleantrue是否允许编辑。
dataSheetSnapshot | nullnull初始工作簿数据。
serverUrlstringREST API 基础 URL(保存/加载)。
wsUrlstringWebSocket URL(协作)。
tokenstringJWT 认证令牌。
userIdstring当前用户 ID。
usernamestring当前用户显示名称。
overridesArray[]Univer 依赖注入覆盖。
onChangeFunction数据变更回调。
onSaveFunction保存成功回调。
onErrorFunction错误处理回调。

JitSheet Facade

The main entry point. All sub-APIs are accessed via its properties.

主入口类。所有子 API 通过其属性访问。

Property / MethodDescription
sheet.dataDataAPI — cell-level CRUD and snapshot operations.
sheet.sheetsSheetAPI — sheet (tab) management.
sheet.ioIOAPI — Excel/JSON import and export.
sheet.permissionPermissionAPI — edit/readonly toggling and protection.
sheet.collabCollabAPI — real-time collaboration.
on(event, handler)Subscribe to an event. Returns unsubscribe function.
once(event, handler)Subscribe once — auto-removes after first call.
destroy()Destroy the instance and release all resources.
reinit(snapshot)Fully reinitialize with new data (destroys and recreates engine).
resize()Trigger layout recalculation (after container resize).
focus()Focus the editor container.
属性 / 方法说明
sheet.dataDataAPI — 单元格增删改查与快照操作。
sheet.sheetsSheetAPI — 工作表(标签页)管理。
sheet.ioIOAPI — Excel/JSON 导入导出。
sheet.permissionPermissionAPI — 编辑/只读切换与保护。
sheet.collabCollabAPI — 实时协作。
on(event, handler)订阅事件。返回取消订阅函数。
once(event, handler)订阅一次 — 首次触发后自动移除。
destroy()销毁实例并释放所有资源。
reinit(snapshot)使用新数据完全重新初始化(销毁并重建引擎)。
resize()触发布局重计算(容器大小变化后调用)。
focus()聚焦编辑器容器。

DataAPI sheet.data

Cell-level data CRUD and full workbook snapshot operations.

单元格数据增删改查和工作簿快照操作。

MethodDescription
getData()Get complete workbook snapshot (all sheets, styles, drawings).
setData(snapshot)Replace entire workbook data with a new snapshot.
clearData()Reset to a blank single-sheet workbook.
getCellValue(sheetId, row, col)Get a single cell's value.
setCellValue(sheetId, row, col, value)Set a single cell's value.
setCells(sheetId, cellValue)Set multiple cells at once. Format: { [row]: { [col]: ICellData } }
getSheetData(sheetId?)Get data for a single sheet (defaults to active sheet).
patchFromSnapshot(remote)Apply remote snapshot by patching only changed cells. Returns true on success, false if full reinit is needed.
方法说明
getData()获取完整工作簿快照(所有工作表、样式、图形)。
setData(snapshot)用新快照替换整个工作簿数据。
clearData()重置为空白单工作表。
getCellValue(sheetId, row, col)获取单个单元格的值。
setCellValue(sheetId, row, col, value)设置单个单元格的值。
setCells(sheetId, cellValue)批量设置多个单元格。格式:{ [row]: { [col]: ICellData } }
getSheetData(sheetId?)获取单个工作表数据(默认为活动工作表)。
patchFromSnapshot(remote)通过补丁方式应用远端快照(仅同步变更的单元格)。成功返回 true,结构性变更返回 false
// Read & write cells | 读写单元格
const val = sheet.data.getCellValue('sheet1', 0, 0)
sheet.data.setCellValue('sheet1', 0, 0, 'Hello World')

// Batch write | 批量写入
sheet.data.setCells('sheet1', {
  0: { 0: { v: 'Name' }, 1: { v: 'Age' } },
  1: { 0: { v: 'Alice' }, 1: { v: 30 } },
})

// Smart patch from server | 从服务端智能补丁
const ok = sheet.data.patchFromSnapshot(remoteSnapshot)
if (!ok) sheet.reinit(remoteSnapshot)

SheetAPI sheet.sheets

Sheet (tab) management — create, delete, rename, list, and switch sheets.

工作表(标签页)管理 — 创建、删除、重命名、列表和切换工作表。

MethodDescription
getSheets()Get all sheets. Returns SheetInfo[].
getActiveSheet()Get the currently active sheet.
createSheet(name?)Create a new sheet. Returns the new sheet ID.
deleteSheet(sheetId)Delete a sheet by ID. Cannot delete the last sheet.
renameSheet(sheetId, name)Rename a sheet.
switchSheet(sheetId)Switch the active sheet tab.
方法说明
getSheets()获取所有工作表。返回 SheetInfo[]
getActiveSheet()获取当前活动工作表。
createSheet(name?)创建新工作表。返回新表 ID。
deleteSheet(sheetId)按 ID 删除工作表。不能删除最后一个表。
renameSheet(sheetId, name)重命名工作表。
switchSheet(sheetId)切换活动工作表标签。
// Manage sheets | 管理工作表
const sheets = sheet.sheets.getSheets()
const newId = sheet.sheets.createSheet('Q1 Revenue')
sheet.sheets.switchSheet(newId)
sheet.sheets.renameSheet(newId, 'Q1 Revenue (Final)')

IOAPI sheet.io

Import and export workbook data in Excel (.xlsx) and JSON formats.

以 Excel (.xlsx) 和 JSON 格式导入导出工作簿数据。

MethodDescription
importExcel(file)Import an Excel file (File object) into the editor.
exportExcel(filename?)Export as .xlsx Blob. If filename provided, triggers download.
importJSON(data)Import JSON data (validates and loads as snapshot).
exportJSON()Export current data as a deep-cloned JSON snapshot.
方法说明
importExcel(file)导入 Excel 文件(File 对象)到编辑器。
exportExcel(filename?)导出为 .xlsx Blob。传入文件名则触发下载。
importJSON(data)导入 JSON 数据(校验并加载为快照)。
exportJSON()导出当前数据为深拷贝的 JSON 快照。
// Export to Excel | 导出 Excel
await sheet.io.exportExcel('report.xlsx')

// Import from file input | 从文件输入导入
const file = fileInput.files[0]
await sheet.io.importExcel(file)

// JSON round-trip | JSON 往返
const json = sheet.io.exportJSON()
localStorage.setItem('backup', JSON.stringify(json))
sheet.io.importJSON(JSON.parse(localStorage.getItem('backup')))

PermissionAPI sheet.permission

Runtime permission toggling and sheet-level protection.

运行时权限切换与工作表级保护。

MethodDescription
getMode()Returns 'edit' or 'readonly'.
isEditable()Returns true if currently in edit mode.
setEditable()Switch to editable mode. Removes readonly overlay.
setReadonly()Switch to readonly mode. Adds overlay mask.
setSheetProtection(sheetId, config)Set sheet-level protection rules (password, cell locking, etc.).
方法说明
getMode()返回 'edit''readonly'
isEditable()返回当前是否处于编辑模式。
setEditable()切换到可编辑模式。移除只读遮罩。
setReadonly()切换到只读模式。添加遮罩层。
setSheetProtection(sheetId, config)设置工作表级保护规则(密码、单元格锁定等)。
// Toggle based on user role | 根据用户角色切换
if (user.role === 'viewer') {
  sheet.permission.setReadonly()
}

// Sheet protection | 工作表保护
sheet.permission.setSheetProtection('sheet1', {
  password: 'secret',
  selectLockedCells: true,
  formatCells: false,
  insertRows: false,
  deleteRows: false,
})

CollabAPI sheet.collab

Real-time collaboration via Yjs + y-websocket. Uses cell-level sync for minimal latency.

基于 Yjs + y-websocket 的实时协作。采用单元格级同步以实现最低延迟。

MethodDescription
connect(roomId)Connect to a collaboration room.
disconnect()Disconnect and cleanup resources.
getStatus()Returns 'idle' | 'connecting' | 'connected' | 'disconnected'.
getOnlineUsers()Returns the list of online users CollabUser[].
onStatusChange(cb)Register callback for connection status changes.
onUsersChange(cb)Register callback for online user list changes.
broadcastCursor(row, col, sheetId)Broadcast cursor position to peers.
pushSnapshot(snapshot)Manually push full snapshot to peers (e.g. after save).
方法说明
connect(roomId)连接到协作房间。
disconnect()断开连接并清理资源。
getStatus()返回 'idle' | 'connecting' | 'connected' | 'disconnected'
getOnlineUsers()返回在线用户列表 CollabUser[]
onStatusChange(cb)注册连接状态变更回调。
onUsersChange(cb)注册在线用户列表变更回调。
broadcastCursor(row, col, sheetId)向对端广播光标位置。
pushSnapshot(snapshot)手动推送完整快照到对端(例如保存后)。
// Connect to collaboration | 连接协作
await sheet.collab.connect('doc-123')

sheet.on('collab:users', (users) => {
  console.log('Online:', users.map(u => u.name))
})

sheet.on('collab:status', (status) => {
  console.log('Connection:', status)
})

Events EventBus

事件 EventBus

EventPayloadDescription
changeSheetSnapshotFired on any data modification.
saveSheetSnapshotFired after a successful save.
selectionSelectionEventCell selection changed.
scrollScrollEventViewport scrolled.
zoomZoomEventZoom level changed.
tab:switchTabSwitchEventActive sheet tab switched.
collab:statusCollabStatusConnection status changed.
collab:usersCollabUser[]Online user list updated.
collab:cursorCollabCursor[]Peer cursor positions changed.
permission:changePermissionModePermission mode toggled.
errorErrorAn error occurred.
readyvoidSDK fully initialized.
destroyvoidSDK destroyed.
事件载荷说明
changeSheetSnapshot任何数据修改时触发。
saveSheetSnapshot保存成功后触发。
selectionSelectionEvent单元格选区变更。
scrollScrollEvent视口滚动。
zoomZoomEvent缩放级别变更。
tab:switchTabSwitchEvent活动工作表标签切换。
collab:statusCollabStatus连接状态变化。
collab:usersCollabUser[]在线用户列表更新。
collab:cursorCollabCursor[]对端光标位置变化。
permission:changePermissionMode权限模式切换。
errorError发生错误。
readyvoidSDK 初始化完成。
destroyvoidSDK 已销毁。

Types TypeScript

类型定义 TypeScript

interface SheetSnapshot {
  id?: string
  name?: string
  sheets: Record<string, SheetData>
  sheetOrder: string[]
  styles?: Record<string, any>
  resources?: any[]
  drawings?: DrawingData[]
}

interface SheetData {
  id: string
  name: string
  cellData: Record<number, Record<number, CellData>>
  rowCount?: number
  columnCount?: number
  rowData?: Record<number, { h?: number }>
  columnData?: Record<number, { w?: number }>
  mergeData?: MergeRange[]
}

interface CellData {
  v?: any        // Cell value
  f?: string     // Formula
  s?: string | number  // Style id
  t?: number     // Cell type
  p?: any        // Rich text paragraph
}

interface SheetInfo {
  id: string
  name: string
  index: number
  isActive: boolean
  rowCount: number
  columnCount: number
}

interface ProtectionConfig {
  password?: string
  selectLockedCells?: boolean
  formatCells?: boolean
  insertRows?: boolean
  deleteRows?: boolean
  sort?: boolean
  autoFilter?: boolean
}

interface SelectionEvent { row: number; col: number; sheetId: string }
interface ScrollEvent { top: number; left: number; raw?: any }
interface ZoomEvent { ratio: number }
interface TabSwitchEvent { sheetId: string }

interface CollabUser { userId: string; name: string; color: string; clientId: number }
interface CollabCursor { clientId: number; userId: string; name: string; color: string; row: number; col: number; sheetId: string }

type PermissionMode = 'edit' | 'readonly'
type CollabStatus = 'idle' | 'connecting' | 'connected' | 'disconnected'

@jitword/sheet-sdk v0.1.0 — Built on JitSheet