下面结合一个实例演示用Python-docx包创建和编辑Word文档的一般过程。
在Python IDLE Shell窗口输入下面的命令行,导入Python-docx包,用 构造函数Document创建一个空白文档doc。
code.python
>>> import docx
>>> doc=docx.Document()
用doc对象的add_paragraph方法创建一个新段落pg。
code.python
>>> pg=doc.add_paragraph('创建一个新段落')
创建第2个新段落pg2。给段落用add_run方法添加一个字符序列。字符序列中文本的字体名称为Calibri,字体倾斜、字体大小为20磅。
code.python
>>> pg2=doc.add_paragraph()
>>> run=pg2.add_run('hellohellohello') #创建第1个字符序列
>>> fnt=run.font
>>> fnt.name='Calibri' #设置字体名称
>>> fnt.italic=True #设置字体倾斜
>>> from docx.shared import Pt
>>> fnt.size=Pt(20) #设置字体大小
在段落pg2中继续添加一个字符序列run2,序列中字体名称为黑体,加粗,字体颜色为绿色,添加下划线。
code.python
>>> run2=pg2.add_run('办公自动化WordWordWordWordWordWord') #创建第2个字符序列
>>> fnt2=run2.font
>>> fnt2.name='黑体'
>>> fnt2.bold=True #加粗
>>> from docx.shared import RGBColor
>>> fnt2.color.rgb=RGBColor(0x00, 0xFF, 0x00) #RGB着色
>>> from docx.enum.text import WD_UNDERLINE
>>> fnt2.underline=WD_UNDERLINE.DOT_DASH #下划线
在文档中添加一个2行2列的表格,给表格中添加文本。
code.python
tbl=doc.add_table(rows=2, cols=2)
tbl.cell(0,0).text='cell_00'
tbl.cell(0,1).text='cell_01'
tbl.cell(1,0).text='cell_10'
tbl.cell(1,1).text='cell_11'
保存文档。
code.python
>>> doc.save('D:\\test.docx')
在D盘下找到刚刚保存的文档,打开,如图7-1所示。
图7-1 创建Word文档