The Problem
Currently I am developing a Word add-in that provides template functionality for a client. I would like to place a ContentControl that contains a single cell table near the cursor. The Javascript API offers this functionality as can be seen here (ContentControl class). Unfortunately, it is possible to place the table before or after the contents of the control, but it is not possible to replace the contents with the table. Whenever I try to achieve the latter, I get a InvalidArgument exception.
Similarly I am unable to directly add a table (without a ContentControl) in the document at the selection. The same exception is thrown. In this case however, it does not matter which location option is specified (before, after, replace the content, etc).
The technology that is used is React and typescript.
Content Control Table
private placeTableControl() {
Word.run(function (context) {
var values = [["Apple"]];
let selectionRange = context.document.getSelection();
let contentControl = selectionRange.insertContentControl();
// This works
// let table = contentControl.insertTable(1, 1, 'Start', values);
// This doesn't
let table = contentControl.insertTable(1, 1, 'Replace', values);
return context.sync()
.catch(function (error) {
console.log(error);
});
});
}
Adding Table Without ContentControl
private placeTable() {
Word.run(function (context) {
var values = [["Apple"]];
let selectionRange = context.document.getSelection();
// This doesn't work.
let table = selectionRange.insertTable(1, 1, 'Replace', values);
// Neither does this.
//let table = selectionRange.insertTable(1, 1, 'Start', values);
// Or this.
//let table = selectionRange.insertTable(1, 1, 'End', values);
return context.sync()
.catch(function (error) {
console.log(error);
});
});
}
PARTIALLY SOLVED - Suggestion Cindy Meister
Cindy Meister suggested that it might have something to do with paragraphs. Tables should be located in a paragraph. Because of my mistake in specifying a simple array instead of a 2D array, I was not able to make it work. This seems to be working now. I will now try to make it work with a content control.
private placeTable() {
Word.run(function (context) {
var values = [["Apple"]];
var selectionRange = context.document.getSelection();
var paragraph = selectionRange.insertParagraph("", "Before");
return context.sync()
.then(function () {
paragraph.insertTable(1, 1, "Before", values);
})
.then(context.sync)
.catch(function (error) {
console.log(error);
});
});
}
SIMILAR QUESTIONS
Found a similar question here.