简体   繁体   中英

password is not getting applied when i protect sheet

I am using Excel API's to protect an Excel Sheet. I tried to do as they have mentioned in the documentation, but the Sheet is not protected by a password. It is simply getting protected without a password.

The code I am trying is as follow:

Excel.run(function (ctx) {
    var sheet = ctx.workbook.worksheets.getItem("Sheet1");
    var range = sheet.getRange("A1:B3").format.protection.locked = false;
    sheet.protection.protect({
        allowInsertRows: true
    }, "mypassword");
    return ctx.sync();
}).catch(function (error) {
    console.log("Error: " + error);
    if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
});

What is going wrong that password is not getting applied ?

You're actually doing the opposite of what you want here. When you set allowInsertRows: true you are unprotecting row insertion. Since you're not protecting anything, the password you provided is simply ignored.

You need to set allowInsertRows: false to disable the ability to insert rows. Once this happens, the user will need to provide a password to unprotect the sheet:

Excel.run(function (ctx) {
    var sheet = ctx.workbook.worksheets.getItem("Sheet1");
    sheet.protection.protect({
        allowInsertRows: false
    }, "mypassword");
    return ctx.sync();
}).catch(function (error) {
    console.log("Error: " + error);
    if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
});

As an aside, this line is entirely unused and wouldn't work regardless. The locked property is Read-Only:

var range = sheet.getRange("A1:B3").format.protection.locked = false;

Update: I just noticed the documentation contains this sample (which clearly is where you got your code from):

Excel.run(function (ctx) {
    var sheet = ctx.workbook.worksheets.getItem("Sheet1");
    var range = sheet.getRange("A1:B3").format.protection.locked = false;
    sheet.protection.protect({
        allowInsertRows: true
    });
    return ctx.sync();
}).catch(function (error) {
    console.log("Error: " + error);
    if (error instanceof OfficeExtension.Error) {
        console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
});

This sample is wrong on several of levels. I'll make sure the sample gets updated ASAP. I'm sorry for the confusion this resulted in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM