I'm having an issue with columnWidth not actually setting and showing in Excel 2016. Below is where my Excel.run function is:
_columns = columns;
var headers = [];
var numCols = _columns.length;
var letter = columnToLetter(numCols); //for perspective, this becomes "P"
for (var i = 0; i < numCols; i++) {
var header = [];
header.push(_columns[i].header);
headers.push(header); //basically an array of arrays, where each entry is ["some string"]
}
var ranges = [];
Office.context.document.bindings.addFromNamedItemAsync(['Sheet1!A', letter].join(':'), 'table', { id: 'table' });
Excel.run(function (context) {
var sheet = context.workbook.worksheets.getItem("Sheet1");
for (var i = 0; i < numCols; i++) {
var range = sheet.getCell(0, i);
range.load(['values', 'text', 'format/columnWidth']);
ranges.push(range);
}
return context.sync().then(function () {
for (var i = 0; i < numCols; i++) {
ranges[i].values = [headers[i]]; //now each range, which is essentially one cell, has one value in values. values = [["some string"]]
headerFormatFn(ranges[i]);
context.sync();
}
})
.catch(function (err) { console.error(err); })
});
and the actual formatting happens in the headerFormatFn(ranges[i]):
function headerFormatFn(cell) {
cell.format.font.bold = true;
cell.format.borders.getItem(1).style = 'Continuous';
cell.format.columnWidth = 80;
}
I've checked support for ExcelApi in my Excel 2016 and i know autofitColumns() isn't supported so I gather that's why the function doesn't work. I'll need to update Excel 2016 for that. However, columnWidth is a property that is supported in ExcelApi 1.1 and so it is supported in my version of Excel 2016.
It's odd because format.font.bold
and format.borders
works just fine. It appears that just setting the columnWidth is not working. See below for a view of the resulting worksheet:
Resulting Excel 2016 Worksheet
I can't tell if this has something to do with context
, or if maybe we're setting up our Excel Add-in wrong. Any help would be greatly appreciated, and if any more information is needed let me know.
-------UPDATE 1-------
In response to answer by @Michael, I made these changes:
I changed my Excel.run to:
Excel.run(function (context) {
var sheet = context.workbook.worksheets.getItem("Sheet1");
for (var i = 0; i < numCols; i++) {
var range = sheet.getCell(0, i);
range.load(['values', 'text', 'format/*']);
ranges.push(range);
}
for (var i = 0; i < numCols; i++) {
ranges[i].values = [headers[i]];
headerFormatFn(ranges[i]);
}
return context.sync()
.catch(function (err) { console.error(err); })
});
and i'm using border.getItemAt(0).style = 'Continuous'
now:
try {
console.log("1");
cell.format.font.bold = true;
console.log("2");
cell.format.borders.getItemAt(0).style = 'Continuous';
console.log("3");
cell.format.columnWidth = 80;
}
catch(error)
{
console.log(error);
}
The logs of 1, 2, and 3 show that the loop completes then gives an OfficeExtensionError
of InvalidArgument
after the loop on the context.sync() call.