获取一系列单元格的填充颜色officejs



我是office.js和制作外接程序的新手,我正在尝试制作Excel的外接程序。有一件事我遇到了一个问题,看起来应该很容易,但事实并非如此。我只是想得到所选单元格的背景色。据我所知,我需要遍历每个选定的单元格,并单独检查fill.color值,这很好,只是我在尝试读取此属性时不断出错。

Error PropertyNotLoaded: The property 'color' is not available. Before reading the property's value, call the load method on the containing object and call "context.sync()" on the associated request context.

我不太明白为什么我必须为此运行context.sync((,因为它已经在运行,并且我正试图使用Visual Studio已经为插件生成的代码。

这个错误让人困惑,因为我可以像这样设置颜色而没有任何问题。这是我为获得填充颜色而添加的代码。第一行被注释掉了,但为所选单元格添加了橙色填充,没有问题。我添加这个只是为了看看我是否能读出一个我知道已经设置好的值。不过,我正在尝试为所选范围获取用户定义的填充。第二行是抛出错误的位置。

//sourceRange.getCell(i, j).format.fill.color = "orange"; // this sets the color no problem when uncommented
$('#fa-output').append("color: " + sourceRange.getCell(i,j).format.fill.color + "<br>"); //this is where it can't get the fill color

我使用的是Visual Studio生成的示例,它将随机生成9个随机数字单元格,并突出显示所选范围中的最高数字。以下是此方法的完整代码:

// Run a batch operation against the Excel object model
Excel.run(function (ctx) {
// Create a proxy object for the selected range and load its properties
var sourceRange = ctx.workbook.getSelectedRange().load("values, rowCount, columnCount, format");
// Run the queued-up command, and return a promise to indicate task completion
return ctx.sync()
.then(function () {
var highestRow = 0;
var highestCol = 0;
var highestValue = sourceRange.values[0][0];
// Find the cell to highlight
for (var i = 0; i < sourceRange.rowCount; i++) {
for (var j = 0; j < sourceRange.columnCount; j++) {
//sourceRange.getCell(i, j).format.fill.color = "orange"; // this sets the color no problem when uncommented
$('#fa-output').append("color: " + sourceRange.getCell(i,j).format.fill.color + "<br>"); //this is where it can't get the fill color
if (!isNaN(sourceRange.values[i][j]) && sourceRange.values[i][j] > highestValue) {
highestRow = i;
highestCol = j;
highestValue = sourceRange.values[i][j];
}
}
}
cellToHighlight = sourceRange.getCell(highestRow, highestCol);
sourceRange.worksheet.getUsedRange().format.font.bold = false;
// Highlight the cell
cellToHighlight.format.font.bold = true;
$('#fa-output').append("<br>The highest value is " + highestValue);
})
.then(ctx.sync);
})
.catch(errorHandler);

您的代码中有很多注释掉的代码,这些代码很难阅读。

无论如何,这是意料之中的行为。当您想读取工作簿中对象的属性时,必须先加载((,然后同步((。正是加载和同步将属性的值从工作簿带到外接程序中的JavaScript中,以便您可以读取它。您的代码正在尝试读取尚未首先加载的属性。下面是一个简单的例子:

const cell = context.workbook.getActiveCell();
cell.load('format/fill/color');
await context.sync();
console.log(cell.format.fill.color);

ES5版本:

const cell = context.workbook.getActiveCell();
cell.load('format/fill/color');
return context.sync()
.then(function () {
console.log(cell.format.fill.color);
});    

您还应该看看Range.getCellProperties((方法,它是负载的一种包装器。

最新更新