0%

Python Word自动化

本文介绍 python-docx

安装

前置条件 已安装 easy_install
1
easy_install python-docx

操作

打开及保存文件:

1
2
3
from docx import Document  
document = Document('test.docx')
document.save('test.docx')

添加标题:

1
document.add_heading('test text',0) 

添加表格:

1
2
3
4
5
6
7
8
9
10
table = document.add_table(rows=2, cols=3)
hdr_cells = table.rows[0].cells

hdr_cells[0].text = u'身高'
hdr_cells[1].text = u'体重'
hdr_cells[2].text = u'年龄'
hdr_cells = table.rows[1].cells
hdr_cells[0].text = u'183CM'
hdr_cells[1].text = u'80KG'
hdr_cells[2].text = u'23'

添加图片:

1
document.add_picture(u'图片.png')

调整文本位置格式为居中:

1
2
3
4
5
6
7
from docx import Document  
from docx.enum.text import WD_ALIGN_PARAGRAPH
document = Document('test.docx')
paragraph = document.add_paragraph('123')

paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
document.save('test.docx')

调整左缩进0.3英寸:

1
2
3
4
5
document = Document('test.docx')  
paragraph = document.add_paragraph('this is test for left_indent with inches')
paragraph_format = paragraph.paragraph_format
paragraph_format.left_indent = Inches(0.3)
document.save('test.docx')

首行缩进:

1
paragraph_format.first_line_indent = Inches(0.3) 

行距:

1
paragraph_format.line_spacing = Pt(18)

字体格式&&字体颜色:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
p = document.add_paragraph()  
run = p.add_run('test typeface')
font = run.font

# 设置字体样式
font.name = 'Calibri'
# 设置字体大小
font.size = Pt(55)
# 加粗
run.font.bold = True
# 斜体
run.font.italic = True
# 下划线
run.font.underline = True

p.add_run('color')
font = test.font
# 以RGB方式设置颜色
from docx.shared import RGBColor
font.color.rgb = RGBColor(0x42, 0x24 , 0xE9)

参考

http://blog.csdn.net/u011932355/article/details/51769803
http://www.cnblogs.com/deepwaterplan/articles/6664796.html
https://sourceforge.net/projects/pywin32/files/pywin32/
https://python-docx.readthedocs.io/en/latest/# api-documentation
http://www.jb51.net/article/65054.htm