这是 Office 脚本 API 的当前限制。目前,请避免在类构造函数中调用 Office Script API。
解决此限制的一种方法是创建一个调用 Office 脚本 API 的方法:
function main(workbook: ExcelScript.Workbook)
{
const info = getInfo(workbook);
console.log(JSON.stringify(info.getVals()));
}
function getInfo(workbook: ExcelScript.Workbook) {
const tbl: ExcelScript.Table = workbook.getTable('test');
const tblValues: (string | number | boolean)[][] = tbl.getRangeBetweenHeaderAndTotal().getValues();
const info = new Info(tbl, tblValues);
return info;
}
class Info {
private table: ExcelScript.Table;
private vals: string[][];
constructor(table: ExcelScript.Table, vals: (string | number | boolean)[][]) {
// avoid calling Office Script APIs inside of class constructors.
this.table = table;
this.vals = vals as string[][];
}
getVals() {
return this.vals;
}
}
该方法可以作为类的静态方法添加:
function main(workbook: ExcelScript.Workbook)
{
const info = Info.create(workbook);
console.log(JSON.stringify(info.getVals()));
}
class Info {
private table: ExcelScript.Table;
private vals: string[][];
constructor(table: ExcelScript.Table, vals: (string | number | boolean)[][]) {
// avoid calling Office Script APIs inside of class constructors.
this.table = table;
this.vals = vals as string[][];
}
static create(workbook: ExcelScript.Workbook) {
const tbl: ExcelScript.Table = workbook.getTable('test');
const tblValues: (string | number | boolean)[][] = tbl.getRangeBetweenHeaderAndTotal().getValues();
const info = new Info(tbl, tblValues);
return info;
}
getVals() {
return this.vals;
}
}
一般来说,就编程最佳实践而言,构造函数避免包含复杂逻辑可能会很方便。