基础使用:
1、创建一个document文档对象
2、向文档中添加段落
3、添加标题
4、添加分页符
5、添加列表
6、添加图片
7、设置段落风格
8、使用加粗和倾斜
9、设定字体样式
基础使用
1.创建一个document文档对象
from docx import Document document = Document()
2.向文档中添加段落 添加一段话:
paragraph = document.add_paragraph(‘Lorem ipsum dolor sit amet.’)
(调用后会返回一个Paragraphs段落对象的引用)
可将上面返回的对象作为一个游标,在已有段落之前加入:
prior_paragraph = paragraph.insert_paragraph_before(‘Lorem ipsum’)
3.添加标题
默认为top-level标题
document.add_heading(‘The REAL meaning of the universe’)
可由level参数指定标题级别
document.add_heading(‘The role of dolphins’, level=2)
4.添加分页符
document.add_page_break()
5.添加列表
table = document.add_table(rows=2, cols=2)
(返回一个Tables对象)
还可对Tables对象中的单元格cel l进行操作:
cel l = table. cel l(0, 1)
向其中添加内容:
cel l.tex t = ‘parrot, pos s ibl y dead’
还可以一行行的操作:
row = table.rows [1] row. cel l s [0].tex t = ‘Foo bar to you.’ row. cel l s [1].tex t = 'And a heart y foo bar to you too s ir!
并且rows和columns是可迭代的,
例如: for row in table.rows: for cell in row.cells: print(cell.text) 用len() 查询rows或columns的个数: row_count = len(table.rows) col_count = len(table.columns) 继续添加行: row