Python办公自动化之Word

Python操作Word

    • 1、Python操作Word概述
    • 2、写入Word
      • 2.1、标题
      • 2.2、章节与段落
      • 2.3、字体与引用
      • 2.4、项目列表
      • 2.5、分页
      • 2.6、表格
      • 2.7、图片
    • 3、读取Word
      • 3.1、读取文档
      • 3.2、读取表格
    • 4、将Word表格保存到Excel
    • 5、格式转换
      • 5.1、Doc转Docx
      • 5.2、Word转PDF

1、Python操作Word概述


python-docx模块是用于创建和处理Microsoft Word文档的一个Python第三方库,提供了全套的Word操作,是最常用的Word工具

官方文档参考:https://python-docx.readthedocs.io/en/latest/

安装:

pip install python-docx

基本概念:

  • Document:Word文档对象,多个文档对象互相独立
  • Paragraph:段落对象,一个Word文档由多个段落组成
  • Run:节段对象,每个段落由多个节段组成

常用功能:

from docx import Document                  # 用于创建文档
from docx.shared import Inches, Cm, Pt     # 单位
from docx.oxml.ns import qn                # 用于中文字体设置
from docx.shared import RGBColor           # 用于字体颜色设置
from docx.enum.text import WD_COLOR_INDEX, WD_PARAGRAPH_ALIGNMENT    # 用于字体背景颜色、段落对齐格式设置
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT               # 用于单元格垂直对齐

2、写入Word

2.1、标题

注意:只能设置0-9级标题

# 1)新建空白文档
doc = Document()
# 2)设置默认字体、字号和中文字体(可选)
style = doc.styles['Normal']
'''
style.font.size = Pt(16)
style.font.name = u'微软雅黑'
style._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')
'''
# 3)添加文档标题:add_heading(text, level=1)
title = doc.add_heading('标题', 0)
# 4)标题居中
title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# 5)保存文档
doc.save(r'C:\Users\cc\Desktop\test.docx')

Python办公自动化之Word_第1张图片

2.2、章节与段落

# 1、段落
# 1)创建段落(正文):add_paragraph(text, style=None)
p1 = doc.add_paragraph("段落1")
# 2)格式
# 设置段落两端对齐
p1.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
# 首行缩进两个字符
p1.paragraph_format.first_line_indent = Cm(0.74)
# 其他缩进:
'''
# 左缩进(英寸)
p1.paragraph_format.left_indent = Inches(0.5)
# 右缩进(磅)
p1.paragraph_format.right_indent = Pt(20)
'''
# 设置行间距:1.5倍行距
p1.paragraph_format.line_spacing = 1.5
# 段前间距(磅)
p1.paragraph_format.space_before = Pt(5)
# 段后间距(磅)
p1.paragraph_format.space_after = Pt(10)
# 创建一级标题
doc.add_heading('一级标题', 1)
# 创建二级标题
doc.add_heading('二级标题', 2

你可能感兴趣的:(#,自动化,#,数据分析,#,Python,python,word)