应用边框格式

时间:2017-08-21 11:25:18

标签: office-js

我尝试设置与新创建的工作表关联的一系列单元格。

我最近的2次(失败)尝试是:

Excel.run(function (context) {
    const newSheet = context.workbook.worksheets.add("New sheet 1");
    newSheet.activate();
    const values = [
        ["Row 1", "Row 1", "Row 1"],
        ["Row 2", "Row 2", "Row 2"]
    ]
    newSheet.getRange("A1").getResizedRange(values.length - 1, values[0].length - 1).values = values;
    context.sync().then(function () {
        newSheet.getRange("A2").getResizedRange(0, output[0].length - 1).foramt = {borderTopStyle: "thin"};
        return context.sync();
    });
});

Excel.run(function (context) {
    const newSheet = context.workbook.worksheets.add("New sheet 1");
    newSheet.activate();
    const values = [
        ["Row 1", "Row 1", "Row 1"],
        ["Row 2", "Row 2", "Row 2"]
    ]
    newSheet.getRange("A1").getResizedRange(values.length - 1, values[0].length - 1).values = values;
    context.sync().then(function () {

        // The difference is here
        newSheet.getRange("A2").getResizedRange(0, values[0].length - 1).foramt.borderTopStyle = "thin";
        return context.sync();
    });
});

确定一系列细胞样式的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

首先,关于您发布的代码的整体结构/内容的一些意见/建议:

  • 请务必始终包含错误处理逻辑,否则在您不知道错误的情况下,事情可能会无声地失败。
  • 对于您的场景,只需要一个context.sync()(最后),因为您之前所做的事情(即将数据写入工作表并将格式应用于工作表)可以简单排队并在最后一个context.sync()中一起执行。
  • 您的代码包含拼写错误(foramt而不是格式),并且指的是RangeFormat对象(borderTopStyle)上不存在的属性名称。如果您使用TypeScript而不是纯JavaScript,则会自动为您标记此类错误。

这是一段代码片段,展示了如何设置指定范围的边框(基于您发布的代码的结构,但经过修改以包含上述反馈):

Excel.run(function (context) {

    // create new sheet, add 2 rows of data
    const newSheet = context.workbook.worksheets.add("New sheet 1");
    newSheet.activate();
    const values = [
        ["Row 1", "Row 1", "Row 1"],
        ["Row 2", "Row 2", "Row 2"]
    ]
    newSheet.getRange("A1").getResizedRange(values.length - 1, values[0].length - 1).values = values;

    // set top border for the second row of data
    newSheet.getRange("A2").getResizedRange(0, values[0].length - 1).format.borders.getItem('EdgeTop').style = 'Continuous';

    return context.sync();
})
    .catch(function (error) {
        console.log('error: ' + error);
        if (error instanceof OfficeExtension.Error) {
            console.log('Debug info: ' + JSON.stringify(error.debugInfo));
        }
    });
}
相关问题