gpt4 book ai didi

javascript - Office js 条件格式

转载 作者:行者123 更新时间:2023-11-29 21:01:43 29 4
gpt4 key购买 nike

我目前正在尝试使用 Office JS API 1.6 在 Excel 中实现条件格式设置。我编写了以下代码来实现文本比较格式设置。

function textComparisonFormatting() {
// Run a batch operation against the Excel object model
Excel.run(function (ctx) {

// Create a proxy object for the active worksheet
var sheet = ctx.workbook.worksheets.getActiveWorksheet();

//Queue a command to write the sample data to the specified range
//in the worksheet and bold the header row
var range = sheet.getRange("A2:E8");

var conditionalFormat = range.conditionalFormats.add(Excel.ConditionalFormatType.textComparison);

conditionalFormat.textComparison.load(["rule","format/*","format/fill"]);

//Run the queued commands, and return a promise to indicate task completion
return ctx.sync(conditionalFormat).then(function(conditionalFormat){

conditionalFormat.textComparison.rule.text = "Qtr";
conditionalFormat.textComparison.rule.operator = "BeginsWith";
conditionalFormat.textComparisonformat.fill.color = "red";
});
})
.then(function () {
app.showNotification("Success");
console.log("Success!");
})
.catch(function (error) {
// Always be sure to catch any accumulated errors that bubble up from the Excel.run execution
app.showNotification("Error: " + error);
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
}

当我尝试设置颜色时,代码抛出 InvalidObjectPath 错误。如果我尝试在 Excel.Run() 中设置颜色,那么它将不起作用,因为我无法访问对象属性。有什么办法可以解决这些问题吗?

最佳答案

您应该对代码进行一些更改:

  1. 您不需要加载任何内容和同步,因为您正在写入属性,而不是读取它们。

  2. 没有ConditionalFormatType.textComparison。您需要 ConditionalFormatType.containsText

  3. 运算符是驼峰式的:beginsWith,而不是 BeginsWith

  4. 应该有一个“.”在 textComparisonformat 之间。

这段代码有效:

function applyTextFormat() {
Excel.run(function (context) {
var sheet = ctx.workbook.worksheets.getActiveWorksheet();
var range = sheet.getRange("A2:E8");
var conditionalFormat = range.conditionalFormats
.add(Excel.ConditionalFormatType.containsText);
conditionalFormat.textComparison.format.fill.color = "red";
conditionalFormat.textComparison.rule = { operator: Excel.ConditionalTextOperator.beginsWith, text: "Qtr" };

return context.sync();
});
}

更新:根据 OP 的要求:该文档尚未在 dev.office.com 上发布。您需要转到 GitHub 上 office-js-docs 存储库的一个特殊分支。打开这个页面,可以看到conditional*.md格式的所有文件: ExcelJs_OpenSpec/reference/excel

关于javascript - Office js 条件格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46115604/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com