How can I stop python-docx from inserting a carriage return before my cell text












0














I want a paragraph inside a cell, but I get a stray carriage return which pushes down the text by one line:



enter image description here



My code:



from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Cm


document = Document()
document.add_heading("The Heading", 1).alignment = WD_ALIGN_PARAGRAPH.CENTER

table = document.add_table(rows=0, cols=2)
table.style = 'Table Grid'
for i in range(3):
row_cells = table.add_row().cells
row_cells[0].text = 'row {}, col 1'.format(i)
row_cells[0].width = Cm(3)
row_cells[1].width = Cm(8)
p = row_cells[1].add_paragraph()
p.add_run('This is an example of')
p.add_run(' some text').bold = True
p.add_run(' in a table cell.')

document.save('test.docx')


How can I get the cell text to align at the top of the cell without the stray CR? And how should I be setting the cell widths to 3 cm and 8 cm: setting _Cell.width isn't respected.










share|improve this question



























    0














    I want a paragraph inside a cell, but I get a stray carriage return which pushes down the text by one line:



    enter image description here



    My code:



    from docx import Document
    from docx.enum.text import WD_ALIGN_PARAGRAPH
    from docx.shared import Cm


    document = Document()
    document.add_heading("The Heading", 1).alignment = WD_ALIGN_PARAGRAPH.CENTER

    table = document.add_table(rows=0, cols=2)
    table.style = 'Table Grid'
    for i in range(3):
    row_cells = table.add_row().cells
    row_cells[0].text = 'row {}, col 1'.format(i)
    row_cells[0].width = Cm(3)
    row_cells[1].width = Cm(8)
    p = row_cells[1].add_paragraph()
    p.add_run('This is an example of')
    p.add_run(' some text').bold = True
    p.add_run(' in a table cell.')

    document.save('test.docx')


    How can I get the cell text to align at the top of the cell without the stray CR? And how should I be setting the cell widths to 3 cm and 8 cm: setting _Cell.width isn't respected.










    share|improve this question

























      0












      0








      0







      I want a paragraph inside a cell, but I get a stray carriage return which pushes down the text by one line:



      enter image description here



      My code:



      from docx import Document
      from docx.enum.text import WD_ALIGN_PARAGRAPH
      from docx.shared import Cm


      document = Document()
      document.add_heading("The Heading", 1).alignment = WD_ALIGN_PARAGRAPH.CENTER

      table = document.add_table(rows=0, cols=2)
      table.style = 'Table Grid'
      for i in range(3):
      row_cells = table.add_row().cells
      row_cells[0].text = 'row {}, col 1'.format(i)
      row_cells[0].width = Cm(3)
      row_cells[1].width = Cm(8)
      p = row_cells[1].add_paragraph()
      p.add_run('This is an example of')
      p.add_run(' some text').bold = True
      p.add_run(' in a table cell.')

      document.save('test.docx')


      How can I get the cell text to align at the top of the cell without the stray CR? And how should I be setting the cell widths to 3 cm and 8 cm: setting _Cell.width isn't respected.










      share|improve this question













      I want a paragraph inside a cell, but I get a stray carriage return which pushes down the text by one line:



      enter image description here



      My code:



      from docx import Document
      from docx.enum.text import WD_ALIGN_PARAGRAPH
      from docx.shared import Cm


      document = Document()
      document.add_heading("The Heading", 1).alignment = WD_ALIGN_PARAGRAPH.CENTER

      table = document.add_table(rows=0, cols=2)
      table.style = 'Table Grid'
      for i in range(3):
      row_cells = table.add_row().cells
      row_cells[0].text = 'row {}, col 1'.format(i)
      row_cells[0].width = Cm(3)
      row_cells[1].width = Cm(8)
      p = row_cells[1].add_paragraph()
      p.add_run('This is an example of')
      p.add_run(' some text').bold = True
      p.add_run(' in a table cell.')

      document.save('test.docx')


      How can I get the cell text to align at the top of the cell without the stray CR? And how should I be setting the cell widths to 3 cm and 8 cm: setting _Cell.width isn't respected.







      python-3.x ms-word python-docx






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 '18 at 16:28









      xnx

      15.3k43672




      15.3k43672
























          1 Answer
          1






          active

          oldest

          votes


















          2














          I worked this out: you get a free paragraph with each cell, so I just needed to add my text runs to this paragraph:



          p = row_cells[1].paragraphs[0]
          p.add_run('This is an example of')
          p.add_run(' some text').bold = True
          p.add_run(' in a table cell.')


          To set the widths, I had to manipulate the columns directly and not set them cell-by-cell (despite this answer):



          table.columns[0].width = Cm(3)
          table.columns[1].width = Cm(8)





          share|improve this answer

















          • 1




            The WordprocessingML ISO spec requires a minimum of one paragraph inside each table cell. This makes some sense from a Word UI perspective as there wouldn't be any place to put your insertion point in the cell otherwise. But it does unfortunately make the code to add cell content special-case for the first paragraph. There's an internal call cell._element.clear_content() which can help. This removes any existing content (including default empty paragraph) and then adding multiple paragraphs is uniform. Note it leaves cell in invalid state if no content is added after.
            – scanny
            Nov 14 '18 at 18:48










          • Thank you for this clarification: I was trying to use the clear function instead and found it wasn't working.
            – xnx
            Nov 15 '18 at 14:28











          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%2f53266317%2fhow-can-i-stop-python-docx-from-inserting-a-carriage-return-before-my-cell-text%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          I worked this out: you get a free paragraph with each cell, so I just needed to add my text runs to this paragraph:



          p = row_cells[1].paragraphs[0]
          p.add_run('This is an example of')
          p.add_run(' some text').bold = True
          p.add_run(' in a table cell.')


          To set the widths, I had to manipulate the columns directly and not set them cell-by-cell (despite this answer):



          table.columns[0].width = Cm(3)
          table.columns[1].width = Cm(8)





          share|improve this answer

















          • 1




            The WordprocessingML ISO spec requires a minimum of one paragraph inside each table cell. This makes some sense from a Word UI perspective as there wouldn't be any place to put your insertion point in the cell otherwise. But it does unfortunately make the code to add cell content special-case for the first paragraph. There's an internal call cell._element.clear_content() which can help. This removes any existing content (including default empty paragraph) and then adding multiple paragraphs is uniform. Note it leaves cell in invalid state if no content is added after.
            – scanny
            Nov 14 '18 at 18:48










          • Thank you for this clarification: I was trying to use the clear function instead and found it wasn't working.
            – xnx
            Nov 15 '18 at 14:28
















          2














          I worked this out: you get a free paragraph with each cell, so I just needed to add my text runs to this paragraph:



          p = row_cells[1].paragraphs[0]
          p.add_run('This is an example of')
          p.add_run(' some text').bold = True
          p.add_run(' in a table cell.')


          To set the widths, I had to manipulate the columns directly and not set them cell-by-cell (despite this answer):



          table.columns[0].width = Cm(3)
          table.columns[1].width = Cm(8)





          share|improve this answer

















          • 1




            The WordprocessingML ISO spec requires a minimum of one paragraph inside each table cell. This makes some sense from a Word UI perspective as there wouldn't be any place to put your insertion point in the cell otherwise. But it does unfortunately make the code to add cell content special-case for the first paragraph. There's an internal call cell._element.clear_content() which can help. This removes any existing content (including default empty paragraph) and then adding multiple paragraphs is uniform. Note it leaves cell in invalid state if no content is added after.
            – scanny
            Nov 14 '18 at 18:48










          • Thank you for this clarification: I was trying to use the clear function instead and found it wasn't working.
            – xnx
            Nov 15 '18 at 14:28














          2












          2








          2






          I worked this out: you get a free paragraph with each cell, so I just needed to add my text runs to this paragraph:



          p = row_cells[1].paragraphs[0]
          p.add_run('This is an example of')
          p.add_run(' some text').bold = True
          p.add_run(' in a table cell.')


          To set the widths, I had to manipulate the columns directly and not set them cell-by-cell (despite this answer):



          table.columns[0].width = Cm(3)
          table.columns[1].width = Cm(8)





          share|improve this answer












          I worked this out: you get a free paragraph with each cell, so I just needed to add my text runs to this paragraph:



          p = row_cells[1].paragraphs[0]
          p.add_run('This is an example of')
          p.add_run(' some text').bold = True
          p.add_run(' in a table cell.')


          To set the widths, I had to manipulate the columns directly and not set them cell-by-cell (despite this answer):



          table.columns[0].width = Cm(3)
          table.columns[1].width = Cm(8)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 12 '18 at 17:09









          xnx

          15.3k43672




          15.3k43672








          • 1




            The WordprocessingML ISO spec requires a minimum of one paragraph inside each table cell. This makes some sense from a Word UI perspective as there wouldn't be any place to put your insertion point in the cell otherwise. But it does unfortunately make the code to add cell content special-case for the first paragraph. There's an internal call cell._element.clear_content() which can help. This removes any existing content (including default empty paragraph) and then adding multiple paragraphs is uniform. Note it leaves cell in invalid state if no content is added after.
            – scanny
            Nov 14 '18 at 18:48










          • Thank you for this clarification: I was trying to use the clear function instead and found it wasn't working.
            – xnx
            Nov 15 '18 at 14:28














          • 1




            The WordprocessingML ISO spec requires a minimum of one paragraph inside each table cell. This makes some sense from a Word UI perspective as there wouldn't be any place to put your insertion point in the cell otherwise. But it does unfortunately make the code to add cell content special-case for the first paragraph. There's an internal call cell._element.clear_content() which can help. This removes any existing content (including default empty paragraph) and then adding multiple paragraphs is uniform. Note it leaves cell in invalid state if no content is added after.
            – scanny
            Nov 14 '18 at 18:48










          • Thank you for this clarification: I was trying to use the clear function instead and found it wasn't working.
            – xnx
            Nov 15 '18 at 14:28








          1




          1




          The WordprocessingML ISO spec requires a minimum of one paragraph inside each table cell. This makes some sense from a Word UI perspective as there wouldn't be any place to put your insertion point in the cell otherwise. But it does unfortunately make the code to add cell content special-case for the first paragraph. There's an internal call cell._element.clear_content() which can help. This removes any existing content (including default empty paragraph) and then adding multiple paragraphs is uniform. Note it leaves cell in invalid state if no content is added after.
          – scanny
          Nov 14 '18 at 18:48




          The WordprocessingML ISO spec requires a minimum of one paragraph inside each table cell. This makes some sense from a Word UI perspective as there wouldn't be any place to put your insertion point in the cell otherwise. But it does unfortunately make the code to add cell content special-case for the first paragraph. There's an internal call cell._element.clear_content() which can help. This removes any existing content (including default empty paragraph) and then adding multiple paragraphs is uniform. Note it leaves cell in invalid state if no content is added after.
          – scanny
          Nov 14 '18 at 18:48












          Thank you for this clarification: I was trying to use the clear function instead and found it wasn't working.
          – xnx
          Nov 15 '18 at 14:28




          Thank you for this clarification: I was trying to use the clear function instead and found it wasn't working.
          – xnx
          Nov 15 '18 at 14:28


















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f53266317%2fhow-can-i-stop-python-docx-from-inserting-a-carriage-return-before-my-cell-text%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

          The Sandy Post

          Danny Elfman

          Pages that link to "Head v. Amoskeag Manufacturing Co."