How to copy range formatting in office.js?

穿精又带淫゛_ 提交于 2019-12-10 17:01:31

问题


Tried the following code that I pieced together from various sources but it doesn't seem to be working. Do I need to go through each individual property and assign them one by one?

Excel.run(function (ctx) {
        var worksheet = ctx.workbook.worksheets.getItem(worksheetName);
        var range = worksheet.getUsedRange();
        range.load(["formulasLocal", "address", "format/*", "format/fill", "format/borders", "format/font"]);

        var newWorksheet = ctx.workbook.worksheets.add(worksheetName + " -Copy");
        return ctx.sync().then(function () {
            var newAddress = range.address.substring(range.address.indexOf("!") + 1);
            newWorksheet.getRange(newAddress).values = range.formulasLocal;
            newWorksheet.getRange(newAddress).format = range.format;
        }).then(ctx.sync);

回答1:


Unfortunately, the scenario is not currently supported (though it is on our backlog). You can get Values and Text and Formulas as arrays, but not the formatting properties.

When you do access something like range.format.fill.color, it will return a value for you if the range is identically formatted; and "null" if the range has multiple colors, and hence there is no single answer to return.

So for now, you would need to go through each cell (range.getCell(i,j)) and put them into your own 2D array, load each range's value individually, then sync, and then use that information to individually apply formatting back. Should be possible with a reasonably small range, but we do realize that there are better solutions possible with more targeted APIs,

~ Michael Zlatkovsky, developer on Office Extensibility team, MSFT




回答2:


There is a group of APIs for doing a batch of set/get Range format. But they are still in preview. You can work with them on build#16.0.11328.20158(win32) or Excel online if you reference the Beta CDN. Here is a simple sample for get a format of a range and set to another range.

var actualData = rangeSrc.getCellProperties({
 format: {
    font: {
           bold: true,
           color: true,
           italic: true,
           name: true,
           underline: true,
           size: true,
           strikethrough: true,
           subscript: true,
           superscript: true,
           tintAndShade: true
    }
 }

});

if you want to see a complete sample, you can import the following gist into Script Lab

PS: please ignore the @odata.type property, it might be temporary. But the rest of the API is expected to be unchanged when it gets released.



来源:https://stackoverflow.com/questions/36670368/how-to-copy-range-formatting-in-office-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!