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.
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.
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?
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.