Python办公自动化之Word

本文介绍了Python使用python-docx模块进行Word操作,包括写入标题、段落、字体、项目列表、表格和图片,读取文档内容,将Word表格导出到Excel,以及利用win32com进行格式转换如Doc转Docx和Word转PDF。
摘要由CSDN通过智能技术生成




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')

在这里插入图片描述

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)

# 2、章节(业)
# 创建一个章节
sec = doc.add_section()
'''
# 设置页面高度、宽度
sec.page_height = Inches(15)
sec.page_width = Inches(10)
# 设置页面的边距
sec.left_margin = Inches(1)
sec.right_margin = Inches(1)
sec.top_margin = Inches(2)
sec.bottom_margin = Inches(2)
# 设置页眉页脚
head = sec.header
foot = sec.footer
head_par = head.paragraphs[0]
head_par.add_run('页眉')
foot_par = foot.paragraphs[0]
foot_par.add_run('页脚')
'''
# 保存
doc
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值