问题
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