Office js条件格式

时间:2017-09-08 11:35:46

标签: javascript excel office-js excel-addins

我目前正在尝试使用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 个答案:

答案 0 :(得分:1)

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

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

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

  3. 运营商是骆驼式的:beginsWith,而不是BeginsWith

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

  5. 此代码段有效:

    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 repo的特殊分支。打开此页面并查看条件* .md形式的所有文件: ExcelJs_OpenSpec/reference/excel