3 Ways to Create a MS Word Table in Office.js Add-In

Here are some handy code snippets for inserting a table into a Word document through a Task Pane Add-In. If you don’t know what that is, you can get up and running with this hello world example.

I demonstrate inserting at the selection, inserting at a named binding and inserting HTML. There is another way, you can insert raw Office Open XML (OOXML), and while that provides the most power and flexibility, it is also by far the most complex way to do it.

Here are a few things that apply to all the Gists to follow:

  • Office.initialize is implemented because it is  necessary to bootstrap the add-in.
  • The initialize method creates a TableData object that is used to generate the Word table.
  • The initialize method also adds a binding to a content control that has been manually added to the document. It gives it an id of “tbl”. It is necessary to add a RichText content control to be the target of a binding.

Insert At Selection:

In this Gist the insertAtSelection() function simply dumps a table into the document wherever the selection cursor is. It does not make use of the binding at all, but does make use of the TableData object.


var myTable;
// The initialize function is required for all apps.
Office.initialize = function (reason) {
$(document).ready(function () {
myTable = new Office.TableData();
myTable.headers = ["First Name", "Last Name", "Grade"];
myTable.rows = [["Brittney", "Booker", "A"], ["Sanjit", "Pandit", "C"], ["Naomi", "Peacock", "B"]];
try {
Office.context.document.bindings.addFromNamedItemAsync('TheTable',
Office.BindingType.Text, { id: 'tbl' },
function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
trace('Control bound. Binding.id: ' + result.value.id + ' Binding.type: ' + result.value.type);
} else {
trace('Error:', result.error.message);
}
});
} catch (e) { trace("Exception: " + e.message); }
});
}
function insertAtSelection() {
try {
Office.context.document.setSelectedDataAsync(myTable, { coercionType: Office.CoercionType.Table },
function (result) {
var error = result.error
if (result.status === Office.AsyncResultStatus.Failed) {
trace(error.name + ": " + error.message);
} else { trace("Success calling addRowsAtSelection"); }
});
} catch (e) { trace("Exception: " + e.message); }
}
function trace(msg) {
$("#trace").append(msg + "<br />");
}

Insert At Binding:
This one creates a Table within the pre-defined content control so that the user does not need to have the cursor in the right place as is the case with Insert at Selection. It is a two step process. First, move the cursor into the target of the binding, then set the table. The documentation states that we should be able to directly setDataAsync() on the binding without having to move the cursor first, but I have found it does not work in Word. I don’t know if it is a bug in the API or a flaw in the documentation but I have submitted feedback to Microsoft with my findings.


var myTable;
// The initialize function is required for all apps.
Office.initialize = function (reason) {
$(document).ready(function () {
myTable = new Office.TableData();
myTable.headers = ["First Name", "Last Name", "Grade"];
myTable.rows = [["Brittney", "Booker", "A"], ["Sanjit", "Pandit", "C"], ["Naomi", "Peacock", "B"]];
try {
Office.context.document.bindings.addFromNamedItemAsync('TheTable',
Office.BindingType.Text, { id: 'tbl' },
function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
trace('Control bound. Binding.id: ' + result.value.id + ' Binding.type: ' + result.value.type);
} else {
trace('Error:', result.error.message);
}
});
} catch (e) { trace("Exception: " + e.message); }
});
}
function insertAtBinding() {
Office.context.document.goToByIdAsync("tbl", Office.GoToType.Binding, function (asyncResult) {
if (asyncResult.status == "failed") {
trace("Go To Binding failed with error: " + asyncResult.error.message);
}
else {
trace("Navigation successful");
try {
Office.context.document.setSelectedDataAsync(myTable,
{
coercionType: Office.CoercionType.Table
},
function (asyncResult) {
if (asyncResult.status == "failed") {
trace("Action failed with error: " + asyncResult.error.message);
} else { trace("Success with addRowsWithoutSelection."); }
});
} catch (e) { trace("Exception: " + e.message); }
}
});
}
function trace(msg) {
$("#trace").append(msg + "<br />");
}

Insert As HTML:
This snippet is not specific to inserting a Table, you can insert any HTML you want. But the easiest way to make a Table that can be formatted is by using HTML. Ideally you would use OOXML, but who has time to figure out that cryptic spec?


var myTable;
// The initialize function is required for all apps.
Office.initialize = function (reason) {
$(document).ready(function () {
myTable = new Office.TableData();
myTable.headers = ["First Name", "Last Name", "Grade"];
myTable.rows = [["Brittney", "Booker", "A"], ["Sanjit", "Pandit", "C"], ["Naomi", "Peacock", "B"]];
try {
Office.context.document.bindings.addFromNamedItemAsync('TheTable',
Office.BindingType.Text, { id: 'tbl' },
function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
trace('Control bound. Binding.id: ' + result.value.id + ' Binding.type: ' + result.value.type);
} else {
trace('Error:', result.error.message);
}
});
} catch (e) { trace("Exception: " + e.message); }
});
}
function addHTML() {
try {
Office.select("bindings#tbl").setDataAsync("<table border='1' width='100%'><thead><tr><th style='background-color:#ff00ff'>Description</th><th>From</th><th>To</th></tr></thead></table>", { coercionType: "html" },
function (asyncResult) {
if (asyncResult.status == "failed") {
trace('Error with addHTML : ' + asyncResult.error.message);
} else { trace("Success calling addHTML()"); }
});
} catch (e) { trace("Exception: " + e.message); }
}
function trace(msg) {
$("#trace").append(msg + "<br />");
}

view raw

InsertAsHTML

hosted with ❤ by GitHub

Now, if you think you want to use the rich capabilities of OOXML, I suggest you create a Table formatted the way you want it in an otherwise blank document. Be careful to avoid spelling mistakes and bad grammar in your table cells to eliminate noise in the xml. When you have the Table the way you like it, go to the folder that contains the document and rename it with a .zip extension. Unzip the file, drill into the Word folder and open document.xml. You can use the contents as a guide for constructing a table by generating your own OOXML. For more info, start here.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s