Search code examples
javascriptms-wordoffice365office-jsoffice-addins

Office.js: ContentControl in table broken after inserting row


I'm using Microsoft® Word for Microsoft 365 MSO (Version 2307 Build 16.0.16626.20170) 64-bit - which means that Word API is version 1.5. Running add-inn sample "Office Add-in Task Pane project" with JavaScript from Microsoft Tutorial: "Create a Word task pane add-in" - page. enter image description here

Here is my "RUN" button on-click handler:

export async function run() {
  return Word.run(async (context) => {
    /**
     * Create Table
     */
    const data = [
      ["Tokyo", "Beijing", "Seattle"],
      ["Apple", "Orange", "Pineapple"]
    ];
    const table = context.document.body.insertTable(2, 3, "Start", data);
    table.styleBuiltIn = Word.BuiltInStyleName.gridTable5Dark_Accent2;
    table.styleFirstColumn = false;

    /**
     * Selecting first row and inserting ContentControl
     */
    table.rows.getFirst().select("Select");
    let range = context.document.getSelection();
    range.insertContentControl();
    /**
     * At this point ContentControl covers only first row
     */

    /**
     * Inserting new row to the end
     */
    const firstTable = context.document.body.tables.getFirst();
    firstTable.addRows("End", 1, [["New", "Row", "Here"]]);

    /**
     * At this point ContentControl spread for all rows :(    
    */

   await context.sync();
});

In the code above only the first row is inside content control. But after adding a new row firstTable.addRows("End", 1, [["New", "Row", "Here"]]) all rows become inside content control. How to fix it? enter image description here


Solution

  • After some back-and-forth with Office.js the solution (or I would say workaround for Microsoft bug) was found:

    1. Insert Content Control in desired row in the table
    2. Get ooxml string from the table and save it into temp var
    3. Delete ooxml from the table (very important step)
    4. Using DOMParser, convert ooxml string to document
    5. Using xpath, copy/paste desired row inside ooxml document
    6. Using XMLSerializer serialize ooxml back to string
    7. Insert ooxml string back to table with "Replace" option
    8. ...
    9. Profit