我正在使用 Excel API 来保护 Excel 工作表。我试着按照他们在文档中提到的那样做,但工作表不受密码保护。它只是在没有密码的情况下得到保护。
我正在尝试的代码如下:
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));
}
});
没有应用密码是怎么回事?
最佳答案
你实际上在做与你想要的相反的事情。当您设置 allowInsertRows: true
时,您将取消保护 行插入。由于您没有保护任何东西,您提供的密码将被忽略。
您需要设置allowInsertRows: false
来禁用插入行的能力。一旦发生这种情况,用户将需要提供密码才能取消对工作表的保护:
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));
}
});
顺便说一句,这条线完全没有用过,无论如何都不会起作用。 locked
属性是只读的:
var range = sheet.getRange("A1:B3").format.protection.locked = false;
更新:我刚刚注意到 documentation包含此示例(这显然是您从中获取代码的地方):
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));
}
});
这个样本在几个层面上是错误的。我会确保示例得到尽快更新。对于由此造成的困惑,我深表歉意。
关于javascript - 保护工作表时未应用密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49572230/