使用 python-docx 时如何在 table 单元格中列出多行?
How to list multiple lines in a table cell while using python-docx?
我是 Python(3.8.8) 的新手。
我想使用 python-docx(0.8.10) 创建一个带有 tables 的文件。
当时我试图将包含项目的列表放入 table 的某个单元格中,
我发现我无法为每个项目切换换行符,即使它们都以 '\n' 结尾。
请参考代码:
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')
我想要的结果是这样的:
然而我的代码结果是这样的:
任何人都可以给我一些关于如何解决这个问题的提示吗?
感谢您的宝贵时间!
在将文本分配给 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')
我是 Python(3.8.8) 的新手。 我想使用 python-docx(0.8.10) 创建一个带有 tables 的文件。 当时我试图将包含项目的列表放入 table 的某个单元格中, 我发现我无法为每个项目切换换行符,即使它们都以 '\n' 结尾。
请参考代码:
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')
我想要的结果是这样的:
然而我的代码结果是这样的:
任何人都可以给我一些关于如何解决这个问题的提示吗? 感谢您的宝贵时间!
在将文本分配给 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')