python操作word-基础

创建word文档

安装

pip install python-docx

创建word文档

from docx import Document

# 创建word文档
doc1 = Document()
# 保存文档
doc1.save('./创建word文档.docx')

打开文档

doc1 = Document('./文档.docx')
# 保存文档
doc1.save('./文档.docx')

编写内容

标题

doc1.add_paragraph('欢迎使用Python创建Word', style='Title')
doc1.add_heading('欢迎使用Python创建Word', 0)
doc1.add_heading('Python操作 增加1级标题', 1)
doc1.add_heading('Python操作 增加2级标题', 2)

段落

# 段落
par1 = doc1.add_paragraph('在如今信息爆炸的时代,高效的办公自动化成为提高工作效率的必要手段。')
# 段落后面追加内容
par1.add_run('现在就开始学习Word办公自动化,让您的工作更加高效、专业和出色')

列表 - 无序

doc1.add_paragraph('java', style='List Bullet')
doc1.add_paragraph('js', style='List Bullet')
doc1.add_paragraph('python', style='List Bullet')
doc1.add_paragraph('lua', style='List Bullet')
doc1.add_paragraph('c++', style='List Bullet')

列表 - 有序

doc1.add_paragraph('Python', style='List Number')
doc1.add_paragraph('HTML', style='List Number')
doc1.add_paragraph('JS', style='List Number')
doc1.add_paragraph('Flask', style='List Number')

引用

doc1.add_paragraph('这个是一个引用内容', style='Intense Quote')

图片

# 图片
pic = doc1.add_picture('./bg.jpg')
# 获取文档的宽度
page_width = doc1.sections[0].page_width
# 获取文档的左边距
page_left_width = doc1.sections[0].left_margin
# 获取中间内容的宽度
content_width = page_width - page_left_width * 2
# 获取图片应该缩小的比例(如果图片或者页面宽度值太高,有可能程序无法计算,可以考虑同时缩小几倍)
sc = (content_width / 100) / (pic.width / 100)
# 修改图片的宽、高
pic.width = int(pic.width * sc)
pic.height = int(pic.height * sc)

表格

# 增加表格
table = doc1.add_table(rows=1, cols=3)
# 设置表格的边框样式
table.style = 'Table Grid'
# 设置表格字段
cells = table.rows[0].cells
cells[0].text = '编号'
cells[1].text = '姓名'
cells[2].text = '职业'
# 表格数据
data = (
    (1, '吕小布', '将军'),
    (2, '诸葛亮', '军事'),
    (3, '刘备', '主攻'),
)
# 添加数据
for i, n, w in data:
    tmp_cell = table.add_row().cells
    tmp_cell[0].text = str(i)
    tmp_cell[1].text = n
    tmp_cell[2].text = w

读取文档

from docx import Document

# 打开文档
doc1 = Document('./文档.docx')
# 读取数据-段落
for p in doc1.paragraphs:
    print(p.text)
# 读取表格
for t in doc1.tables:
    for row in t.rows:
        for c in row.cells:
            print(c.text, end=' ')
        print()

猜你喜欢

转载自blog.csdn.net/m0_63040701/article/details/135687434