基础使用
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对象中的单元格cell进行操作:
cell = table.cell(0, 1)
向其中添加内容:
cell.text = 'parrot, possibly dead'
还可以一行行的操作:
row = table.rows[1]
row.cells[0].text = 'Foo bar to you.'
row.cells[1].text = 'And a hearty foo bar to you too sir!'
并且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 = table.add_row()
对于变长的表格,可以这样做:
# get table data -------------
items = (
(7, '1024', 'Plush kittens'),
(3, '2042', 'Furbees'),
(1, '1288', 'French Poodle Collars, Deluxe'),
)
# add table ------------------
table = document.add_table(1, 3)
# populate header row --------
heading_cells = table.rows[0].cells
heading_cells[0].text = 'Qty'
heading_cells[1].text = 'SKU'
heading_cells[2].text = 'Description'
# add a data row for each item
for item in items:
cells = table.add_row().cells
cells[0].text = str(item.qty)
cells[1].text = item.sku
cells[2].text = item.desc
设定表格样式风格:
table.style = 'LightShading-Accent1'
6.添加图片
document.add_picture('image-filename.png')
图片大小,可直接设定宽高:
from docx.shared import Inches
document.add_picture('image-filename.png',width=Inches(1.0))
7.设置段落风格
可在创建paragraph时设定:
document.add_paragraph('Lorem ipsum dolor sit amet.', style='ListBullet')
也可之后设定:
paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.')
paragraph.style = 'List Bullet'
8.使用加粗和倾斜
在通过add_paragraph()添加一段文字之后,还可以在这段中添加更多文字,通过add_run()
paragraph = document.add_paragraph('Lorem ipsum ')
paragraph.add_run('dolor sit amet.')
(这个方法会返回一个Run对象)
可对Run对象设定是否加粗、倾斜
paragraph.add_run('dolor').bold = True
is equivalent to:
run = paragraph.add_run('dolor')
run.bold = True
9.设定字体样式
paragraph = document.add_paragraph('Normal text, ')
paragraph.add_run('text with emphasis.', 'Emphasis')
is equivalent to:
paragraph = document.add_paragraph('Normal text, ')
run = paragraph.add_run('text with emphasis.')
run.style = 'Emphasis'