I'm a new guy to Python(3.8.8). I would like to create a file with tables by using python-docx(0.8.10). At the time I'm trying to put a list with items into a certain cell of a table, I found out that I can't switch a newline for every item, even when they're all end up with '\n'.
please refer to the code:
from docx import Document
list1 = ['this is the first line.\n', 'this is the second line.\n', 'this is the third line.\n']
doc1 = Document()
table1 = doc1.add_table(rows=3, cols=2, style = 'Table Grid')
table1.cell(2, 1).text = list1
doc1.save('C:\\temps\\doc1.docx')
My desired outcome is something like this:
However the outcome of my code is like this:
Can anyone give me some hints about how to solve this problem? Thanks for your time!
Change the text to a single str before assigning it to cell.text
:
from docx import Document
list1 = ['this is the first line.\n', 'this is the second line.\n', 'this is the third line.\n']
doc1 = Document()
table1 = doc1.add_table(rows=3, cols=2, style = 'Table Grid')
# --- list of str is joined into single space-separated str ---
table1.cell(2, 1).text = " ".join(list1)
doc1.save('C:\\temps\\doc1.docx')