OpenXML clone table multiple times

84 Views Asked by At

I have a word document with a table inside. I am trying to clone that table multiple times inside the document. The code below successfully does that job, but after I save and try to open the file I get a warning - 'Word found unreadable content in {filename}...'. If I clone the table only once I don't get any warning when I try to open the document. I am using OpenXml 2.20.0.

    Table sourceTable = main.Document.Body.Descendants<Table>()
        .FirstOrDefault(table => table.Descendants<TableCaption>()
        .FirstOrDefault()?.Val == "Table");

    var tables = new List<Table>();

    for (int i = 0; i < 2; i++)
    {
        sourceTable.InsertAfterSelf<Table>((Table)sourceTable.Clone());
    }
    sourceTable.Remove();
1

There are 1 best solutions below

0
J Scott On

The open xml apis can be a bit finicky, especially when it comes to how data is stored. Since the single clone works when you remove the table, I'd look for either a list of the tables somewhere else in the document (that you would need to add your cloned table to), or for a unique id on the cloned table where word expects there to only be one such table. Then again, I'm guessing here. The only way to know for sure is to try and imulate how the word program would update the document to perform the same task.

The best advice I can give is to do the change manually and inspect the changes word makes to the XML as part of that. This relies on the fact that you can change your document extension from .docx to .zip and inspect the document XML. The steps would be:

  1. Start with a document with a table in it, where the table has not yet been copied. This is your baseline.
  2. Create a new copy of your document where you will make the change manually.
  3. Copy the table in the document, manually simulating the process you want to automate.
  4. Update both the baseline and the updated document extensions to .zip
  5. Use a tool like beyond compare to compare the contents of each zip to isolate the changes done by the word program.