Skip to main content

Restrict Table Area Editing

Function Description

The first row of the table is the header, fixed and not allowed to be modified. The remaining rows are data areas, allowed to be modified.

Code Example

var app;

// Initialize
async function init(url, selector) {
app = await ZOfficeSDK.mount(url, selector, true);
await app.ready();

// Enable area editing protection
await app.ActiveDocument.protect(Word.ProtectionType.EditArea);
await protectForTable();
}

// Allow rows 2 to last row of table to be editable, other areas not editable
async function protectForTable() {
const table = await getTableByBookmark('bookmarkName');
// const table = await getTableByTitle('title'); Or get table by table title

const rowCount = await table.Rows.count;
const sRow = await table.Rows.item(2); // Get table row 2
const eRow = await table.Rows.item(rowCount); // Get last row of table
const sRowRange = await sRow.range;
const eRowRange = await eRow.range;
const range = await app.ActiveDocument.getSelection();
range.buildRange(sRowRange.start, eRowRange.end); // Build Range from row 2 to last row of table

// Restrict rows 2 to last row of this table to be editable, other areas not editable
// To only allow certain users to edit, change second parameter to { "user": ["userId", "userId"] }
await app.ActiveDocument.PermMarks.add(
'ProtectionAreaName',
{"group": ["everyone"]},
range
);
}

// Table is within a bookmark, get table by bookmark
async function getTableByBookmark(bookmarkName) {
const bm1 = await app.ActiveDocument.Bookmarks.item(bookmarkName);
const range = await bm1.range;
const table = await range.Tables.item(1);
return table;
}

// Table has title set, get table by table title
// Table title can be set in two ways:
// 1. Through SDK API: Table.setTitle('xxx')
// 2. Right-click table -> Table Properties -> Enter title
async function getTableByTitle(title) {
const table = await app.ActiveDocument.Tables.item(title);
return table;
}