0%

python小菜鸟备忘录:用python写入word

我又突发奇想,想直接用python写入word,嘻嘻。


安装

好像brew安不了,只能用 pip。

1
python3 -m pip install python-docx

新建与保存

1
2
3
4
5
import docx 

doc = docx.Document() #新建文档
...
doc.save('xxx.docx') #保存文档

写入

写入一段话(Paragraph)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.') #写入
prior_paragraph = paragraph.insert_paragraph_before('Lorem ipsum') #在paragraph这段话之前插入一段话

#调整整体格式
document.add_paragraph('Lorem ipsum dolor sit amet.', style='ListBullet') #有序列表 style名称和word一样

#调整整体格式方法2
paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.')
paragraph.style = 'List Bullet'

#加缩进
from docx.shared import Inches
paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.')
paragraph_format = paragraph.paragraph_format
paragraph_format.left_indent = Inches(0.5) #这个是缩进数值

#右边缩进
paragraph_format.right_indent = Pt(24)

#首行缩进
paragraph_format.first_line_indent = Inches(-0.25) #正号是缩进 负值则是第一行冒出去

#设置字体
from docx.shared import Pt
from docx.shared import RGBColor
from docx.oxml.ns import qn

pa = paragraphs[10].add_run("XXX") #设置run
pa.font.size = Pt(10) #设置字号
pa.font.bold = True #设置粗体
pa.font.color.rgb = RGBColor(255, 0, 0) #设置颜色
pa.font.name = "Times New Roman" #设置英文字体

#设置中文字体
pa.font.name = u'微软雅黑'
pa._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')

添加标题(headings)

1
2
3
document.add_heading('The REAL meaning of the universe') #添加一级标题(在word里对应‘Heading 1’
document.add_heading('The role of dolphins', level=2) #添加小标题,可以包括1-9
document.add_heading('The role of dolphins', level=0) #添加title

插入表格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
table = document.add_table(rows=2, cols=2) #插入表格
cell = table.cell(0, 1) #按照行-列access每个cell,注意从0开始计数
cell.text = 'parrot, possibly dead' #写入cell

row1 = table.rows[1] #第2行,每个table可以.rows,每个row可以.cells
row.cells[0].text = 'Foo bar to you.' #第2行第一列
row.cells[1].text = 'And a hearty foo bar to you too sir!'

#遍历每一个cell
for row in table.rows:
for cell in row.cells:
print(cell.text)

#添加行
row = table.add_row()

#get行数和列数
row_count = len(table.rows)
col_count = len(table.columns)

#使用word内置的表格style,只要在word里找到想要的style,把空格去掉再写到这里就可以了
table.style = 'LightShading-Accent1'

#批量写入栗子
# 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

#设置表格属性
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_ALIGN_VERTICAL

tables[0].cell(0,0).width = Cm(3) #每列必须相同,不相同取最大值
tables[0].rows[0].height = Cm(0.7)
tables[0].cell(0,0).paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER #水平对齐
tables[0].cell(0,0).vertical_alignment = WD_ALIGN_VERTICAL.CENTER #垂直对齐

插入图片

1
2
3
4
5
document.add_picture('image-filename.png')

#设置图片大小
from docx.shared import Inches
document.add_picture('image-filename.png', width=Inches(1.0))

粗体/斜体

1
2
3
4
5
6
7
8
9
10
11
12
#粗体和斜体只能在run(字节)上添加
paragraph = document.add_paragraph('Lorem ipsum ')
run = paragraph.add_run('dolor')
run.bold = True
run.italic = True
paragraph.add_run(' sit amet.').bold = True

#paragraph也可以不添加任何内容
paragraph = document.add_paragraph()
paragraph.add_run('Lorem ipsum ')
paragraph.add_run('dolor').bold = True
paragraph.add_run(' sit amet.')

加入分页符

1
document.add_page_break()

改变已有文件

打开文档

1
2
3
4
5
#打开文件
document = Document('existing-document-file.docx')

#另存为(注意如果和已有文件名字一样会覆盖)
document.save('new-file-name.docx')

读取文档

1
2
3
paragraphs = document.paragraphs
print(paragraphs[10].text)
type(paragraphs[10].text)

插入文字

1
2
3
4
5
6
aragraphs[10].add_run("XXX")

#另外一种方式 通过for循环paragraphs列表,判断某段落中是否有你的标注信息(定位信息),有的话,就在该段落后面加上文字
for par in document.paragraphs:
if "[sign]" in par.text:
par.add_run("XXX")

插入图片

1
2
run = paragraphs[10].add_run()
run.add_picture("xxx.png", width = Inches(4.5))

栗子:按模版生成固定文件

文档准备

首先准备好一个模版文档

哦对,在这个过程中,我还发现mac 的word如果是末尾加空白的下划线有时候加不上(我做模版的时候一直加不上超生气,好不容易找到方法加上了,想单独录一个视频结果却总成功加上,真是玄学。

比如:

解决方法:Option+shift+空格

准备批量生产代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from docx import Document

#准备写入内容
name="张三"
id_code="104111199009103531"
career="工程师"
working_years="10"
contact="李四"
company="格物厚德股份有限公司"
address="珠海市横琴新区宝华路6号105室-67425"
tel="0756-8627528"

#准备工作
textlist=[name,id_code,career,working_years,company,address,contact,tel]
doc = Document("证明.docx")
count=0

#写入
for p in doc.paragraphs:
print(p.text)
if 'XXX' in p.text:
inline = p.runs
for i in range(len(inline)):
print(i)
if 'XXX' in inline[i].text:
text = inline[i].text.replace('XXX', textlist[count])
inline[i].text = text
count+=1
print(count)
doc.save("%s_证明.docx"%name)

成功啦!

通过excel批量写入

建立excel表

调整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from docx import Document
#准备写入内容
import xlrd
import time
# 当前时间元组
from datetime import datetime
nt=datetime.now()
# 可以输入中文年月日
datestr=nt.strftime('%Y{y}%m{m}%d{d}').format(y='年', m='月', d='日')

xlsx=xlrd.open_workbook('test.xlsx')
sheet=xlsx.sheet_by_index(0)
for row in range(1,sheet.nrows):
doc = Document("证明.docx")
count=0
textlist=[]
for col in range(0,sheet.ncols):
textlist.append(str(sheet.cell_value(row, col)))

for p in doc.paragraphs:
if 'XXX' in p.text:
inline = p.runs
for i in range(len(inline)):
if 'XXX' in inline[i].text:
text = inline[i].text.replace('XXX', textlist[count])
inline[i].text = text
count+=1
if 'X 年 X 月 X 日' in p.text:
inline = p.runs
for i in range(len(inline)):
if 'X 年 X 月 X 日' in inline[i].text:
text = inline[i].text.replace('X 年 X 月 X 日', datestr)
inline[i].text = text

doc.save("%s_证明.docx"%textlist[0])

然后就成功啦!呱唧呱唧!

Reference

【极简Python 自动化办公】Python写入Word文档

说说如何使用 python-docx 写入 word 文档