Python办公自动化解决world文件批量转换


Posted in Python onSeptember 15, 2021

只要是简单重复的工作,就想办法用 Python 来帮你解决吧,人生苦短,你需要 Python。

Word 是办公软件中使用频率非常高的软件之一了,假如你需要调整 100 个 Word 文档的格式保持统一,或者要把 100 个 Word 全部转换为 pdf,那么你就需要 Python 来帮忙了。

python-docx 库简介

python-docx 是一个可以对 Word 进行读写操作的第三方库,可以读取 Word 内容,可以为 Word 文档添加段落、表格、图片、标题,应用段落样式、粗体和斜体、字符样式。

执行如下安装命令即可完成安装:

pip install python-docx

官方文档: https://python-docx.readthedocs.io/

读取 Word

这里我先创建了一个样例,里面有标题、正文、表格:

Python办公自动化解决world文件批量转换

读取 Word 内容的代码如下:

from docx import Document
def view_docs(docx_file):
    # 打开文档1
    doc = Document(docx_file)
    # 读取每段内容
    pl = [ paragraph.text for paragraph in doc.paragraphs]
    # 输出读取到的内容
    for i in pl:
        print(i)
def view_docs_table(docx_file):
    # 打开文档1
    doc = Document(docx_file)
    # 读取每段内容
    tables = [table for table in doc.tables]
    for table in tables:
        for row in table.rows:
            for cell in row.cells:
                print(cell.text, end='  ')
            print()
        print('\n')
 if __name__ == '__main__':
    view_docs("Python自动化办公实战课.docx")
    view_docs_table("Python自动化办公实战课.docx")

运行结果如下:

Python办公自动化解决world文件批量转换 

写入 Word

现在,用 Python 创建一个和刚才一样的 Word 文档:

from docx import Document
from docx.shared import Pt, RGBColor
from docx.oxml.ns import qn
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.table import _Cell
from docx.oxml import OxmlElement 
def set_cell_border(cell: _Cell, **kwargs):
    """
    Set cell`s border
    Usage:
    set_cell_border(
        cell,
        top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
        bottom={"sz": 12, "color": "#00FF00", "val": "single"},
        start={"sz": 24, "val": "dashed", "shadow": "true"},
        end={"sz": 12, "val": "dashed"},
    )
    """
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
 
    # check for tag existnace, if none found, then create one
    tcBorders = tcPr.first_child_found_in("w:tcBorders")
    if tcBorders is None:
        tcBorders = OxmlElement('w:tcBorders')
        tcPr.append(tcBorders)
    # list over all available tags
    for edge in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
        edge_data = kwargs.get(edge)
        if edge_data:
            tag = 'w:{}'.format(edge)
             # check for tag existnace, if none found, then create one
            element = tcBorders.find(qn(tag))
            if element is None:
                element = OxmlElement(tag)
                tcBorders.append(element)
             # looks like order of attributes is important
            for key in ["sz", "val", "color", "space", "shadow"]:
                if key in edge_data:
                    element.set(qn('w:{}'.format(key)), str(edge_data[key]))
document = Document()
document.styles['Normal'].font.name = u'宋体'
document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
##标题
def add_header(text, level, align='center'):
    title_ = document.add_heading(level=level)
    if align == 'center':
        title_.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # 标题居中
    elif align == 'right':
        title_.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT  # 标题居中
    title_run = title_.add_run(text)  # 添加标题内容
    # title_run.font.size = Pt(24)  # 设置标题字体大小
    title_run.font.name = 'Times New Roman'  # 设置标题西文字体
    title_run.font.color.rgb = RGBColor(0, 0, 0)  # 字体颜色
    title_run.element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')  # 设置标题中文字体
add_header(text='Python自动化办公实战', level=1)
add_header(text='Python基础', level=2, align='left')
document.add_paragraph('Python 是一门面向对象的高级编程语言,易学易用,是自动化办公首选的工具。')
add_header('Python玩转图片', level=2, align='left')
document.add_paragraph('图片是工作中接触较多的媒体文件了,你可能需要图片压缩,加水印,文字识别等操作')
records = (
    ('Python 基础', '00:30', '2021-08-01', ''),
    ('Python 玩转图片', '01:00', '2021-08-01', ''),
    ('Python 玩转 Word', '01:00', '2021-08-01', ''),
)
table = document.add_table(rows=1, cols=4)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = '章节'
hdr_cells[1].text = '时长'
hdr_cells[2].text = '日期'
hdr_cells[3].text = '备注'
for cell in hdr_cells:
    set_cell_border(cell,
                    top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
                    bottom={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
                    start={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
                    end={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
                    )
for chapter, time, date, note in records:
    row_cells = table.add_row().cells
    row_cells[0].text = chapter
    row_cells[1].text = time
    row_cells[2].text = date
    row_cells[3].text = note
    for cell in row_cells:
        set_cell_border(cell,
                        top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
                        bottom={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
                        start={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
                        end={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
                        )
document.save('Python自动化办公实战.docx')

其中,为表格添加边框的代码由于比较复杂,单独做为一个函数来调用。

生成的 Word 文档如下所示,其中表格边框的颜色,标题的颜色,字体大小,样式都是可以设置的:

Python办公自动化解决world文件批量转换

其他操作

添加分页符:

document.add_page_break()

添加图片:

document.add_picture('monty-truth.png', width=Inches(1.25))

设置表格的列宽和行高

'''
设置列宽
可以设置每个单元格的宽,同列单元格宽度相同,如果定义了不同的宽度将以最大值准
'''
table.cell(0,0).width=Cm(10)
#设置行高
table.rows[0].height=Cm(2)

表格字体的设定:

from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
#设置整个表格字体属性
table.style.font.size=Pt(18)
table.style.font.color.rgb=RGBColor(255, 0, 0)
table.style.paragraph_format.alignment=WD_PARAGRAPH_ALIGNMENT.CENTER

合并单元格

cell_1=table.cell(1, 0)
cell_2=table.cell(2, 1)
cell_1.merge(cell_2)

修改文档字体:

from docx import Document
from docx.shared import Pt  #设置像素、缩进等
from docx.shared import RGBColor #设置字体颜色
from docx.oxml.ns import qn
doc = Document("xxx.docx")
for paragraph in doc.paragraphs:
    for run in paragraph.runs:
        run.font.bold = True
        run.font.italic = True
        run.font.underline = True
        run.font.strike = True
        run.font.shadow = True
        run.font.size = Pt(18)
        run.font.color.rgb = RGBColor(255,0,255)
        run.font.name = "黑体"
        # 设置像黑体这样的中文字体,必须添加下面 2 行代码
        r = run._element.rPr.rFonts
        r.set(qn("w:eastAsia"),"黑体")
doc.save("xxx.docx")

行间距调整:

paragraph.paragraph_format.line_spacing = 5.0

段前与段后间距调整:

#段前
paragraph.paragraph_format.space_before = Pt(12)
 
#段后    
paragraph.paragraph_format.space_after = Pt(10)

Word 转 pdf

只需要两行代码就可以将 Word 转 pdf,这里使用的是三方库 docx2pdf 使用前先 pip install docx2pdf

具体代码如下所示:

from docx2pdf import convert
convert("Python自动化办公实战.docx", "Python自动化办公实战.docx.pdf")

如果要对某个目录下的 Word 批量转换为 pdf,可以这样:

from docx2pdf import convert
convert("目录路径/")

批量转换为 pdf 时是否非常方便? 

知道了这些小操作,就可以组装大操作,比如后面可以用 Python 将 Word 转换为 pdf 后作为附件发送邮件给其他人。

最后的话

本文分享了一种读写 Word 的方式,在日常工作中如果是重复性的 Word 操作,可考虑 Python 自动化,有问题请留言交流。阅读原文可以查看 gitee 上的代码。

以上就是Python办公自动化解决world批量转换的详细内容,更多关于Python办公自动化的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python 字符串定义
Sep 25 Python
Python内置的字符串处理函数整理
Jan 29 Python
跟老齐学Python之玩转字符串(2)
Sep 14 Python
python字符串连接方法分析
Apr 12 Python
Python实现优先级队列结构的方法详解
Jun 02 Python
Python实现可设置持续运行时间、线程数及时间间隔的多线程异步post请求功能
Jan 11 Python
答题辅助python代码实现
Jan 16 Python
python中计算一个列表中连续相同的元素个数方法
Jun 29 Python
selenium+python 对输入框的输入处理方法
Oct 11 Python
在pycharm中python切换解释器失败的解决方法
Oct 29 Python
python匹配两个短语之间的字符实例
Dec 25 Python
python如何通过闭包实现计算器的功能
Feb 22 Python
Python函数式编程中itertools模块详解
Sep 15 #Python
Python编程中Python与GIL互斥锁关系作用分析
Sep 15 #Python
Python3.10的一些新特性原理分析
Sep 15 #Python
一篇文章带你了解Python和Java的正则表达式对比
Sep 15 #Python
Python编程编写完善的命令行工具
Sep 15 #Python
python可视化之颜色映射详解
python的变量和简单数字类型详解
Sep 15 #Python
You might like
CI框架网页缓存简单用法分析
2018/12/26 PHP
js querySelector和getElementById通过id获取元素的区别
2012/04/20 Javascript
基于javascript的COOkie的操作实现只能点一次
2014/12/26 Javascript
input输入密码变黑点密文的实现方法
2017/01/09 Javascript
jQuery滑动到底部加载下一页数据的实例代码
2017/05/22 jQuery
javascript 产生随机数的几种方法总结
2017/09/26 Javascript
利用vue开发一个所谓的数独方法实例
2017/12/21 Javascript
vue简单封装axios插件和接口的统一管理操作示例
2020/02/02 Javascript
javascript实现多边形碰撞检测
2020/10/24 Javascript
解决vant title-active-color与title-inactive-color不生效问题
2020/11/03 Javascript
分析在Python中何种情况下需要使用断言
2015/04/01 Python
Python正则表达式教程之三:贪婪/非贪婪特性
2017/03/02 Python
python3中str(字符串)的使用教程
2017/03/23 Python
python3.4用函数操作mysql5.7数据库
2017/06/23 Python
Python3 加密(hashlib和hmac)模块的实现
2017/11/23 Python
Python使用正则表达式获取网页中所需要的信息
2018/01/29 Python
PyQt5每天必学之进度条效果
2018/04/19 Python
python读取大文件越来越慢的原因与解决
2019/08/08 Python
PyCharm刷新项目(文件)目录的实现
2020/02/14 Python
在Sublime Editor中配置Python环境的详细教程
2020/05/03 Python
几个CSS3的flex弹性盒模型布局的简单例子演示
2016/05/12 HTML / CSS
Shell如何接收变量输入
2016/08/06 面试题
外贸英语专业求职信范文
2013/12/25 职场文书
物流专业求职计划书
2014/01/10 职场文书
三好学生演讲稿范文
2014/04/26 职场文书
吨的认识教学反思
2014/04/27 职场文书
小学师德标兵先进事迹材料
2014/05/25 职场文书
2014年终个人工作总结
2014/11/07 职场文书
2014最新股权信托合同协议书
2014/11/18 职场文书
2015新年寄语大全
2014/12/08 职场文书
2015年销售员工作总结范文
2015/04/07 职场文书
如何在CocosCreator里画个炫酷的雷达图
2021/04/16 Javascript
golang在GRPC中设置client的超时时间
2021/04/27 Golang
javascript对象3个属性特征
2021/11/17 Javascript
css3中2D转换之有趣的transform形变效果
2022/02/24 HTML / CSS
vue实现Toast组件轻提示
2022/04/10 Vue.js