文章目录
- 1 概述
-
- 2 新建文档
-
- 2.1 空白文档
- 2.2 标题
- 2.3 段落
- 2.4 文本
- 2.5 字体
- 2.6 图片
- 2.7 表格
- 3 扩展
-
1 概述
1.1 第三方库:python-docx
> pip install python-docx
2 新建文档
2.1 空白文档
import docx
from docx import document
doc = docx.Document()
assert isinstance(doc, document.Document)
doc.save('test.docx')
2.2 标题
import docx
from docx import document
doc = docx.Document()
assert isinstance(doc, document.Document)
doc.add_heading(text='Python 操作 Word 教程', level=0)
doc.add_heading(text='第一章:Python 基础', level=1)
doc.add_heading(text='1.1 Python 基础语法', level=2)
doc.save('test.docx')
效果图:
2.3 段落
import docx
from docx import document
doc = docx.Document()
assert isinstance(doc, document.Document)
paragraph = doc.add_paragraph('这是第一个文本段落')
paragraph.insert_paragraph_before("在之前,添加段落")
doc.add_paragraph(text='这是第二个文本段落', style='List Bullet')
doc.save('test.docx')
2.4 文本
import docx
from docx import document
doc = docx.Document()
assert isinstance(doc, document.Document)
paragraph = doc.add_paragraph()
run = paragraph.add_run('这是一个文本')
doc.save('test.docx')
2.5 字体
import docx
from docx import document
from docx.shared import Pt
from docx.shared import RGBColor
doc = docx.Document()
assert isinstance(doc, document.Document)
paragraph = doc.add_paragraph()
run = paragraph.add_run('这是一个文本')
font = run.font
font.name = '微软雅黑'
font.size = Pt(12)
font.color.rgb = RGBColor(255, 0, 0)
font.bold = True
doc.save('test.docx')
2.6 图片
import docx
from docx import document
from docx.shared import Cm
doc = docx.Document()
assert isinstance(doc, document.Document)
doc.add_picture('1.png', width=Cm(10), height=Cm(5))
doc.save('test.docx')
2.7 表格
import docx
from docx import document
doc = docx.Document()
assert isinstance(doc, document.Document)
table = doc.add_table(rows=2, cols=3)
cell = table.cell(0, 0)
cell.text = '我是 A1'
for row in table.rows:
for cell in row.cells:
print(cell.text)
doc.save('test.docx')
3 扩展
3.1 修改文档
import docx
from docx import document
doc = docx.Document('test.docx')
assert isinstance(doc, document.Document)
doc.paragraphs[0].text = '修改第一个段落'
doc.save('test.docx')
3.2 读取文档
import docx
from docx import document
doc = docx.Document('test.docx')
assert isinstance(doc, document.Document)
for p in doc.paragraphs:
print(p.text)
doc.save('test.docx')