Python: Create a “Table Of Contents” with python-docx/lxml












5















I'm trying to automate the creation of .docx files (WordML) with the help of python-docx (https://github.com/mikemaccana/python-docx). My current script creates the ToC manually with following loop:



for chapter in myChapters:
body.append(paragraph(chapter.text, style='ListNumber'))


Does anyone know of a way to use the "word built-in" ToC-function, which adds the index automatically and also creates paragraph-links to the individual chapters?



Thanks a lot!










share|improve this question



























    5















    I'm trying to automate the creation of .docx files (WordML) with the help of python-docx (https://github.com/mikemaccana/python-docx). My current script creates the ToC manually with following loop:



    for chapter in myChapters:
    body.append(paragraph(chapter.text, style='ListNumber'))


    Does anyone know of a way to use the "word built-in" ToC-function, which adds the index automatically and also creates paragraph-links to the individual chapters?



    Thanks a lot!










    share|improve this question

























      5












      5








      5


      2






      I'm trying to automate the creation of .docx files (WordML) with the help of python-docx (https://github.com/mikemaccana/python-docx). My current script creates the ToC manually with following loop:



      for chapter in myChapters:
      body.append(paragraph(chapter.text, style='ListNumber'))


      Does anyone know of a way to use the "word built-in" ToC-function, which adds the index automatically and also creates paragraph-links to the individual chapters?



      Thanks a lot!










      share|improve this question














      I'm trying to automate the creation of .docx files (WordML) with the help of python-docx (https://github.com/mikemaccana/python-docx). My current script creates the ToC manually with following loop:



      for chapter in myChapters:
      body.append(paragraph(chapter.text, style='ListNumber'))


      Does anyone know of a way to use the "word built-in" ToC-function, which adds the index automatically and also creates paragraph-links to the individual chapters?



      Thanks a lot!







      python docx wordml python-docx






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Sep 3 '13 at 15:17









      Joseph jun. MelettukunnelJoseph jun. Melettukunnel

      2,884135485




      2,884135485
























          3 Answers
          3






          active

          oldest

          votes


















          13














          The key challenge is that a rendered ToC depends on pagination to know what page number to put for each heading. Pagination is a function provided by the layout engine, a very complex piece of software built into the Word client. Writing a page layout engine in Python is probably not a good idea, definitely not a project I'm planning to undertake anytime soon :)



          The ToC is composed of two parts:




          1. the element that specifies the ToC placement and things like which heading levels to include.

          2. the actual visible ToC content, headings and page numbers with dotted lines connecting them.


          Creating the element is pretty straightforward and relatively low-effort. Creating the actual visible content, at least if you want the page numbers included, requires the Word layout engine.



          These are the options:




          1. Just add the tag and a few other bits to signal Word the ToC needs to be updated. When the document is first opened, a dialog box appears saying links need to be refreshed. The user clicks Yes and Bob's your uncle. If the user clicks No, the ToC title appears with no content below it and the ToC can be updated manually.


          2. Add the tag and then engage a Word client, by means of C# or Visual Basic against the Word Automation library, to open and save the file; all the fields (including the ToC field) get updated.


          3. Do the same thing server-side if you have a SharePoint instance or whatever that can do it with Word Automation Services.


          4. Create an AutoOpen macro in the document that automatically runs the field update when the document is opened. Probably won't pass a lot of virus checkers and won't work on locked-down Windows builds common in a corporate setting.



          Here's a very nice set of screencasts by Eric White that explain all the hairy details






          share|improve this answer





















          • 1





            Hi scanny, thanks again for the very detailed answer! Cheers

            – Joseph jun. Melettukunnel
            Sep 5 '13 at 8:00



















          4














          Sorry for adding comments to an old post, but I think it may be helpful.
          This is not my solution, but it has been found there: https://github.com/python-openxml/python-docx/issues/36
          Thanks to https://github.com/mustash and https://github.com/scanny



              from docx.oxml.ns import qn
          from docx.oxml import OxmlElement

          paragraph = self.document.add_paragraph()
          run = paragraph.add_run()
          fldChar = OxmlElement('w:fldChar') # creates a new element
          fldChar.set(qn('w:fldCharType'), 'begin') # sets attribute on element
          instrText = OxmlElement('w:instrText')
          instrText.set(qn('xml:space'), 'preserve') # sets attribute on element
          instrText.text = 'TOC \o "1-3" \h \z \u' # change 1-3 depending on heading levels you need

          fldChar2 = OxmlElement('w:fldChar')
          fldChar2.set(qn('w:fldCharType'), 'separate')
          fldChar3 = OxmlElement('w:t')
          fldChar3.text = "Right-click to update field."
          fldChar2.append(fldChar3)

          fldChar4 = OxmlElement('w:fldChar')
          fldChar4.set(qn('w:fldCharType'), 'end')

          r_element = run._r
          r_element.append(fldChar)
          r_element.append(instrText)
          r_element.append(fldChar2)
          r_element.append(fldChar4)
          p_element = paragraph._p





          share|improve this answer


























          • this works for me, thanks.

            – patrick
            May 15 '18 at 13:32











          • instrText.text = 'TOC o "1-3" h z u' # change 1-3 depending on heading levels you need ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 19-20: truncated uXXXX escape

            – Mawg
            Dec 20 '18 at 13:50








          • 1





            Aha! See this page, where @Sup3rGeo says "I also had to escape \o \h \z \u for it to work without errors", after which it works for me. I suggest that you update your otherwise excellent answer. Now, if only there were some way to programmatically update the table of contents ;-)

            – Mawg
            Dec 20 '18 at 13:56






          • 1





            @Mawg Thank you for the suggestion. Will update the comment.

            – Kostiantyn Medvid
            Jan 3 at 1:07













          • Great (+1) ! That will certainly help others in future (it certainly helped me, once I figured out the double escaping). Now, if only there were some way to programmatically update the table of contents ;-)

            – Mawg
            Jan 3 at 7:08



















          0














          @Mawg // Updating ToC



          Had the same issue to update the ToC and googled for it. Not my code, but it works:



          word = win32com.client.DispatchEx("Word.Application")
          doc = word.Documents.Open(input_file_name)
          doc.TablesOfContents(1).Update()
          doc.Close(SaveChanges=True)
          word.Quit()





          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f18595864%2fpython-create-a-table-of-contents-with-python-docx-lxml%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            13














            The key challenge is that a rendered ToC depends on pagination to know what page number to put for each heading. Pagination is a function provided by the layout engine, a very complex piece of software built into the Word client. Writing a page layout engine in Python is probably not a good idea, definitely not a project I'm planning to undertake anytime soon :)



            The ToC is composed of two parts:




            1. the element that specifies the ToC placement and things like which heading levels to include.

            2. the actual visible ToC content, headings and page numbers with dotted lines connecting them.


            Creating the element is pretty straightforward and relatively low-effort. Creating the actual visible content, at least if you want the page numbers included, requires the Word layout engine.



            These are the options:




            1. Just add the tag and a few other bits to signal Word the ToC needs to be updated. When the document is first opened, a dialog box appears saying links need to be refreshed. The user clicks Yes and Bob's your uncle. If the user clicks No, the ToC title appears with no content below it and the ToC can be updated manually.


            2. Add the tag and then engage a Word client, by means of C# or Visual Basic against the Word Automation library, to open and save the file; all the fields (including the ToC field) get updated.


            3. Do the same thing server-side if you have a SharePoint instance or whatever that can do it with Word Automation Services.


            4. Create an AutoOpen macro in the document that automatically runs the field update when the document is opened. Probably won't pass a lot of virus checkers and won't work on locked-down Windows builds common in a corporate setting.



            Here's a very nice set of screencasts by Eric White that explain all the hairy details






            share|improve this answer





















            • 1





              Hi scanny, thanks again for the very detailed answer! Cheers

              – Joseph jun. Melettukunnel
              Sep 5 '13 at 8:00
















            13














            The key challenge is that a rendered ToC depends on pagination to know what page number to put for each heading. Pagination is a function provided by the layout engine, a very complex piece of software built into the Word client. Writing a page layout engine in Python is probably not a good idea, definitely not a project I'm planning to undertake anytime soon :)



            The ToC is composed of two parts:




            1. the element that specifies the ToC placement and things like which heading levels to include.

            2. the actual visible ToC content, headings and page numbers with dotted lines connecting them.


            Creating the element is pretty straightforward and relatively low-effort. Creating the actual visible content, at least if you want the page numbers included, requires the Word layout engine.



            These are the options:




            1. Just add the tag and a few other bits to signal Word the ToC needs to be updated. When the document is first opened, a dialog box appears saying links need to be refreshed. The user clicks Yes and Bob's your uncle. If the user clicks No, the ToC title appears with no content below it and the ToC can be updated manually.


            2. Add the tag and then engage a Word client, by means of C# or Visual Basic against the Word Automation library, to open and save the file; all the fields (including the ToC field) get updated.


            3. Do the same thing server-side if you have a SharePoint instance or whatever that can do it with Word Automation Services.


            4. Create an AutoOpen macro in the document that automatically runs the field update when the document is opened. Probably won't pass a lot of virus checkers and won't work on locked-down Windows builds common in a corporate setting.



            Here's a very nice set of screencasts by Eric White that explain all the hairy details






            share|improve this answer





















            • 1





              Hi scanny, thanks again for the very detailed answer! Cheers

              – Joseph jun. Melettukunnel
              Sep 5 '13 at 8:00














            13












            13








            13







            The key challenge is that a rendered ToC depends on pagination to know what page number to put for each heading. Pagination is a function provided by the layout engine, a very complex piece of software built into the Word client. Writing a page layout engine in Python is probably not a good idea, definitely not a project I'm planning to undertake anytime soon :)



            The ToC is composed of two parts:




            1. the element that specifies the ToC placement and things like which heading levels to include.

            2. the actual visible ToC content, headings and page numbers with dotted lines connecting them.


            Creating the element is pretty straightforward and relatively low-effort. Creating the actual visible content, at least if you want the page numbers included, requires the Word layout engine.



            These are the options:




            1. Just add the tag and a few other bits to signal Word the ToC needs to be updated. When the document is first opened, a dialog box appears saying links need to be refreshed. The user clicks Yes and Bob's your uncle. If the user clicks No, the ToC title appears with no content below it and the ToC can be updated manually.


            2. Add the tag and then engage a Word client, by means of C# or Visual Basic against the Word Automation library, to open and save the file; all the fields (including the ToC field) get updated.


            3. Do the same thing server-side if you have a SharePoint instance or whatever that can do it with Word Automation Services.


            4. Create an AutoOpen macro in the document that automatically runs the field update when the document is opened. Probably won't pass a lot of virus checkers and won't work on locked-down Windows builds common in a corporate setting.



            Here's a very nice set of screencasts by Eric White that explain all the hairy details






            share|improve this answer















            The key challenge is that a rendered ToC depends on pagination to know what page number to put for each heading. Pagination is a function provided by the layout engine, a very complex piece of software built into the Word client. Writing a page layout engine in Python is probably not a good idea, definitely not a project I'm planning to undertake anytime soon :)



            The ToC is composed of two parts:




            1. the element that specifies the ToC placement and things like which heading levels to include.

            2. the actual visible ToC content, headings and page numbers with dotted lines connecting them.


            Creating the element is pretty straightforward and relatively low-effort. Creating the actual visible content, at least if you want the page numbers included, requires the Word layout engine.



            These are the options:




            1. Just add the tag and a few other bits to signal Word the ToC needs to be updated. When the document is first opened, a dialog box appears saying links need to be refreshed. The user clicks Yes and Bob's your uncle. If the user clicks No, the ToC title appears with no content below it and the ToC can be updated manually.


            2. Add the tag and then engage a Word client, by means of C# or Visual Basic against the Word Automation library, to open and save the file; all the fields (including the ToC field) get updated.


            3. Do the same thing server-side if you have a SharePoint instance or whatever that can do it with Word Automation Services.


            4. Create an AutoOpen macro in the document that automatically runs the field update when the document is opened. Probably won't pass a lot of virus checkers and won't work on locked-down Windows builds common in a corporate setting.



            Here's a very nice set of screencasts by Eric White that explain all the hairy details







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 20 '16 at 13:58









            Mad Physicist

            38.5k1679112




            38.5k1679112










            answered Sep 3 '13 at 23:27









            scannyscanny

            10.6k12245




            10.6k12245








            • 1





              Hi scanny, thanks again for the very detailed answer! Cheers

              – Joseph jun. Melettukunnel
              Sep 5 '13 at 8:00














            • 1





              Hi scanny, thanks again for the very detailed answer! Cheers

              – Joseph jun. Melettukunnel
              Sep 5 '13 at 8:00








            1




            1





            Hi scanny, thanks again for the very detailed answer! Cheers

            – Joseph jun. Melettukunnel
            Sep 5 '13 at 8:00





            Hi scanny, thanks again for the very detailed answer! Cheers

            – Joseph jun. Melettukunnel
            Sep 5 '13 at 8:00













            4














            Sorry for adding comments to an old post, but I think it may be helpful.
            This is not my solution, but it has been found there: https://github.com/python-openxml/python-docx/issues/36
            Thanks to https://github.com/mustash and https://github.com/scanny



                from docx.oxml.ns import qn
            from docx.oxml import OxmlElement

            paragraph = self.document.add_paragraph()
            run = paragraph.add_run()
            fldChar = OxmlElement('w:fldChar') # creates a new element
            fldChar.set(qn('w:fldCharType'), 'begin') # sets attribute on element
            instrText = OxmlElement('w:instrText')
            instrText.set(qn('xml:space'), 'preserve') # sets attribute on element
            instrText.text = 'TOC \o "1-3" \h \z \u' # change 1-3 depending on heading levels you need

            fldChar2 = OxmlElement('w:fldChar')
            fldChar2.set(qn('w:fldCharType'), 'separate')
            fldChar3 = OxmlElement('w:t')
            fldChar3.text = "Right-click to update field."
            fldChar2.append(fldChar3)

            fldChar4 = OxmlElement('w:fldChar')
            fldChar4.set(qn('w:fldCharType'), 'end')

            r_element = run._r
            r_element.append(fldChar)
            r_element.append(instrText)
            r_element.append(fldChar2)
            r_element.append(fldChar4)
            p_element = paragraph._p





            share|improve this answer


























            • this works for me, thanks.

              – patrick
              May 15 '18 at 13:32











            • instrText.text = 'TOC o "1-3" h z u' # change 1-3 depending on heading levels you need ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 19-20: truncated uXXXX escape

              – Mawg
              Dec 20 '18 at 13:50








            • 1





              Aha! See this page, where @Sup3rGeo says "I also had to escape \o \h \z \u for it to work without errors", after which it works for me. I suggest that you update your otherwise excellent answer. Now, if only there were some way to programmatically update the table of contents ;-)

              – Mawg
              Dec 20 '18 at 13:56






            • 1





              @Mawg Thank you for the suggestion. Will update the comment.

              – Kostiantyn Medvid
              Jan 3 at 1:07













            • Great (+1) ! That will certainly help others in future (it certainly helped me, once I figured out the double escaping). Now, if only there were some way to programmatically update the table of contents ;-)

              – Mawg
              Jan 3 at 7:08
















            4














            Sorry for adding comments to an old post, but I think it may be helpful.
            This is not my solution, but it has been found there: https://github.com/python-openxml/python-docx/issues/36
            Thanks to https://github.com/mustash and https://github.com/scanny



                from docx.oxml.ns import qn
            from docx.oxml import OxmlElement

            paragraph = self.document.add_paragraph()
            run = paragraph.add_run()
            fldChar = OxmlElement('w:fldChar') # creates a new element
            fldChar.set(qn('w:fldCharType'), 'begin') # sets attribute on element
            instrText = OxmlElement('w:instrText')
            instrText.set(qn('xml:space'), 'preserve') # sets attribute on element
            instrText.text = 'TOC \o "1-3" \h \z \u' # change 1-3 depending on heading levels you need

            fldChar2 = OxmlElement('w:fldChar')
            fldChar2.set(qn('w:fldCharType'), 'separate')
            fldChar3 = OxmlElement('w:t')
            fldChar3.text = "Right-click to update field."
            fldChar2.append(fldChar3)

            fldChar4 = OxmlElement('w:fldChar')
            fldChar4.set(qn('w:fldCharType'), 'end')

            r_element = run._r
            r_element.append(fldChar)
            r_element.append(instrText)
            r_element.append(fldChar2)
            r_element.append(fldChar4)
            p_element = paragraph._p





            share|improve this answer


























            • this works for me, thanks.

              – patrick
              May 15 '18 at 13:32











            • instrText.text = 'TOC o "1-3" h z u' # change 1-3 depending on heading levels you need ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 19-20: truncated uXXXX escape

              – Mawg
              Dec 20 '18 at 13:50








            • 1





              Aha! See this page, where @Sup3rGeo says "I also had to escape \o \h \z \u for it to work without errors", after which it works for me. I suggest that you update your otherwise excellent answer. Now, if only there were some way to programmatically update the table of contents ;-)

              – Mawg
              Dec 20 '18 at 13:56






            • 1





              @Mawg Thank you for the suggestion. Will update the comment.

              – Kostiantyn Medvid
              Jan 3 at 1:07













            • Great (+1) ! That will certainly help others in future (it certainly helped me, once I figured out the double escaping). Now, if only there were some way to programmatically update the table of contents ;-)

              – Mawg
              Jan 3 at 7:08














            4












            4








            4







            Sorry for adding comments to an old post, but I think it may be helpful.
            This is not my solution, but it has been found there: https://github.com/python-openxml/python-docx/issues/36
            Thanks to https://github.com/mustash and https://github.com/scanny



                from docx.oxml.ns import qn
            from docx.oxml import OxmlElement

            paragraph = self.document.add_paragraph()
            run = paragraph.add_run()
            fldChar = OxmlElement('w:fldChar') # creates a new element
            fldChar.set(qn('w:fldCharType'), 'begin') # sets attribute on element
            instrText = OxmlElement('w:instrText')
            instrText.set(qn('xml:space'), 'preserve') # sets attribute on element
            instrText.text = 'TOC \o "1-3" \h \z \u' # change 1-3 depending on heading levels you need

            fldChar2 = OxmlElement('w:fldChar')
            fldChar2.set(qn('w:fldCharType'), 'separate')
            fldChar3 = OxmlElement('w:t')
            fldChar3.text = "Right-click to update field."
            fldChar2.append(fldChar3)

            fldChar4 = OxmlElement('w:fldChar')
            fldChar4.set(qn('w:fldCharType'), 'end')

            r_element = run._r
            r_element.append(fldChar)
            r_element.append(instrText)
            r_element.append(fldChar2)
            r_element.append(fldChar4)
            p_element = paragraph._p





            share|improve this answer















            Sorry for adding comments to an old post, but I think it may be helpful.
            This is not my solution, but it has been found there: https://github.com/python-openxml/python-docx/issues/36
            Thanks to https://github.com/mustash and https://github.com/scanny



                from docx.oxml.ns import qn
            from docx.oxml import OxmlElement

            paragraph = self.document.add_paragraph()
            run = paragraph.add_run()
            fldChar = OxmlElement('w:fldChar') # creates a new element
            fldChar.set(qn('w:fldCharType'), 'begin') # sets attribute on element
            instrText = OxmlElement('w:instrText')
            instrText.set(qn('xml:space'), 'preserve') # sets attribute on element
            instrText.text = 'TOC \o "1-3" \h \z \u' # change 1-3 depending on heading levels you need

            fldChar2 = OxmlElement('w:fldChar')
            fldChar2.set(qn('w:fldCharType'), 'separate')
            fldChar3 = OxmlElement('w:t')
            fldChar3.text = "Right-click to update field."
            fldChar2.append(fldChar3)

            fldChar4 = OxmlElement('w:fldChar')
            fldChar4.set(qn('w:fldCharType'), 'end')

            r_element = run._r
            r_element.append(fldChar)
            r_element.append(instrText)
            r_element.append(fldChar2)
            r_element.append(fldChar4)
            p_element = paragraph._p






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 3 at 1:09

























            answered Feb 5 '18 at 12:09









            Kostiantyn MedvidKostiantyn Medvid

            46047




            46047













            • this works for me, thanks.

              – patrick
              May 15 '18 at 13:32











            • instrText.text = 'TOC o "1-3" h z u' # change 1-3 depending on heading levels you need ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 19-20: truncated uXXXX escape

              – Mawg
              Dec 20 '18 at 13:50








            • 1





              Aha! See this page, where @Sup3rGeo says "I also had to escape \o \h \z \u for it to work without errors", after which it works for me. I suggest that you update your otherwise excellent answer. Now, if only there were some way to programmatically update the table of contents ;-)

              – Mawg
              Dec 20 '18 at 13:56






            • 1





              @Mawg Thank you for the suggestion. Will update the comment.

              – Kostiantyn Medvid
              Jan 3 at 1:07













            • Great (+1) ! That will certainly help others in future (it certainly helped me, once I figured out the double escaping). Now, if only there were some way to programmatically update the table of contents ;-)

              – Mawg
              Jan 3 at 7:08



















            • this works for me, thanks.

              – patrick
              May 15 '18 at 13:32











            • instrText.text = 'TOC o "1-3" h z u' # change 1-3 depending on heading levels you need ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 19-20: truncated uXXXX escape

              – Mawg
              Dec 20 '18 at 13:50








            • 1





              Aha! See this page, where @Sup3rGeo says "I also had to escape \o \h \z \u for it to work without errors", after which it works for me. I suggest that you update your otherwise excellent answer. Now, if only there were some way to programmatically update the table of contents ;-)

              – Mawg
              Dec 20 '18 at 13:56






            • 1





              @Mawg Thank you for the suggestion. Will update the comment.

              – Kostiantyn Medvid
              Jan 3 at 1:07













            • Great (+1) ! That will certainly help others in future (it certainly helped me, once I figured out the double escaping). Now, if only there were some way to programmatically update the table of contents ;-)

              – Mawg
              Jan 3 at 7:08

















            this works for me, thanks.

            – patrick
            May 15 '18 at 13:32





            this works for me, thanks.

            – patrick
            May 15 '18 at 13:32













            instrText.text = 'TOC o "1-3" h z u' # change 1-3 depending on heading levels you need ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 19-20: truncated uXXXX escape

            – Mawg
            Dec 20 '18 at 13:50







            instrText.text = 'TOC o "1-3" h z u' # change 1-3 depending on heading levels you need ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 19-20: truncated uXXXX escape

            – Mawg
            Dec 20 '18 at 13:50






            1




            1





            Aha! See this page, where @Sup3rGeo says "I also had to escape \o \h \z \u for it to work without errors", after which it works for me. I suggest that you update your otherwise excellent answer. Now, if only there were some way to programmatically update the table of contents ;-)

            – Mawg
            Dec 20 '18 at 13:56





            Aha! See this page, where @Sup3rGeo says "I also had to escape \o \h \z \u for it to work without errors", after which it works for me. I suggest that you update your otherwise excellent answer. Now, if only there were some way to programmatically update the table of contents ;-)

            – Mawg
            Dec 20 '18 at 13:56




            1




            1





            @Mawg Thank you for the suggestion. Will update the comment.

            – Kostiantyn Medvid
            Jan 3 at 1:07







            @Mawg Thank you for the suggestion. Will update the comment.

            – Kostiantyn Medvid
            Jan 3 at 1:07















            Great (+1) ! That will certainly help others in future (it certainly helped me, once I figured out the double escaping). Now, if only there were some way to programmatically update the table of contents ;-)

            – Mawg
            Jan 3 at 7:08





            Great (+1) ! That will certainly help others in future (it certainly helped me, once I figured out the double escaping). Now, if only there were some way to programmatically update the table of contents ;-)

            – Mawg
            Jan 3 at 7:08











            0














            @Mawg // Updating ToC



            Had the same issue to update the ToC and googled for it. Not my code, but it works:



            word = win32com.client.DispatchEx("Word.Application")
            doc = word.Documents.Open(input_file_name)
            doc.TablesOfContents(1).Update()
            doc.Close(SaveChanges=True)
            word.Quit()





            share|improve this answer




























              0














              @Mawg // Updating ToC



              Had the same issue to update the ToC and googled for it. Not my code, but it works:



              word = win32com.client.DispatchEx("Word.Application")
              doc = word.Documents.Open(input_file_name)
              doc.TablesOfContents(1).Update()
              doc.Close(SaveChanges=True)
              word.Quit()





              share|improve this answer


























                0












                0








                0







                @Mawg // Updating ToC



                Had the same issue to update the ToC and googled for it. Not my code, but it works:



                word = win32com.client.DispatchEx("Word.Application")
                doc = word.Documents.Open(input_file_name)
                doc.TablesOfContents(1).Update()
                doc.Close(SaveChanges=True)
                word.Quit()





                share|improve this answer













                @Mawg // Updating ToC



                Had the same issue to update the ToC and googled for it. Not my code, but it works:



                word = win32com.client.DispatchEx("Word.Application")
                doc = word.Documents.Open(input_file_name)
                doc.TablesOfContents(1).Update()
                doc.Close(SaveChanges=True)
                word.Quit()






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 14 at 11:34









                sliceoflivesliceoflive

                1




                1






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f18595864%2fpython-create-a-table-of-contents-with-python-docx-lxml%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    How to fix TextFormField cause rebuild widget in Flutter

                    Npm cannot find a required file even through it is in the searched directory