You can set objects + variables in the Template. If you pass an object with the attribute 'tableOfContent', you can fill that attribute in your microflow dependant on your specific document and/or situation.
This is more a stack overflow question. You need to generate the word document in Java and the doc4j is able to do such a thing. See documentation here: https://www.docx4java.org/forums/docx-java-f6/table-of-contents-t187.html