Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

office js - How to lock only dedicated cells via Excel JavaScript API

As documented here I tried to lock only some cells (all cells of a column in my case) but all cells of the whole document are locked and not only the cells of the range. I already tried to lock only some cells like "D1:D5" but again all cells are locked and not only these 5 cells.

This is my code:

function lockColumnHandler() {
    lockColumn("Sheet1", "D:D");
}

function lockColumn(sheetName, columnRange) {
    Excel.run(function (ctx) {
        var sheet = ctx.workbook.worksheets.getItem(sheetName);
        var range = sheet.getRange(columnRange);

        if (range) {
            range.format.protection.locked = true;
        }

        sheet.protection.protect({
            allowAutoFilter: true,
            allowDeleteColumns: true,
            allowDeleteRows: true,
            allowFormatCells: true,
            allowFormatColumns: true,
            allowFormatRows: true,
            allowInsertColumns: true,
            allowInsertHyperlinks: true,
            allowInsertRows: true,
            allowPivotTables: true,
            allowSort: true
        });

        return ctx.sync();
    })
    .catch(errorHandler);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The default state in Excel is that all cells are marked as locked (you can right-click on any cell in Excel, go to Format Cells->Protection and you will find "Locked" is ticked by default).

So in order to lock only these cells, you would have to unlock all cells of the sheet, except the ones you want to lock.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...