Python办公自动化 | 批量word报告生成工具

有时候我们需要按照某种规则生成一种固定模板的word报告,python能够很好的完成这项工作。本文通过一个小示例说明一下如何通过Python实现自动生成word报告。

首先我们需要有一个word报告模板,模板中内置了一些需要修改的关键字,类似这个样子

Python办公自动化 | 批量word报告生成工具_第1张图片

如上图所示,文档中标红的文字都属于关键字,是需要替换的。

这里,我们还需要一份excel表格,用来存储报告的关键内容。

Python办公自动化 | 批量word报告生成工具_第2张图片

到这里,准备工作就做好了,可以开始写代码了。

处理word需要用到python-docx包,先pip安装

pip install python-docx

首先导入用到的包

from docx import Document
import xlrd

编写一个小函数来实现word段落内容和表格内容的替换

def text_chenge(headline, data):
    # 用来替换word段落中的关键字内容,关键字都是excel表格的标题行
    myparagraphs = document.paragraphs
    for paragraph in myparagraphs:
        for run in paragraph.runs:
            run_text = run.text.replace(headline, data)
            run.text = run_text

    # 用来替换word表格中的关键字内容,关键字都是excel表格的标题行
    mytables = document.tables
    for table in mytables:
        for row in table.rows:
            for cell in row.cells:
                cell_text = cell.text.replace(headline, data)
                cell.text = cell_text

打开excel文件,获取报告内容

xlsx = xlrd.open_workbook(r'D:\pycharm\learning\autowork\document\报告数据.xlsx')
table = xlsx.sheet_by_index(0)

遍历excel的单元格,同时打开报告模板文件,按照excel中的数据替换报告模板中的关键字,替换完成后,保存为新文件,文件名为excel中的A列单元格的内容+eSRVCC切换成功率低优化报告.docx
实现代码如下:

xlsx = xlrd.open_workbook(r'D:\pycharm\learning\autowork\document\报告数据.xlsx')
table = xlsx.sheet_by_index(0)

for table_row in range(1, table.nrows):
    document = Document(r'D:\pycharm\learning\autowork\document\报告模板.docx')
    for table_col in range(0, table.ncols):
        text_chenge(str(table.cell(0, table_col).value), str(table.cell(table_row, table_col).value))
        # 将excel表格中的内容替换掉标题行,因为标题行即为报告模板中的关键字

    document.save(f'{str(table.cell(table_row, 0).value)} eSRVCC切换成功率低优化报告.docx')
    print("%s eSRVCC切换成功率低优化报告成功生成!" % str(table.cell_value(table_row, 0)))

执行代码,即可在相同目录下生成多个word报告

完整代码如下:

from docx import Document
import xlrd

def text_chenge(headline, data):
    # 用来替换word段落中的关键字内容,关键字都是excel表格的标题行
    myparagraphs = document.paragraphs
    for paragraph in myparagraphs:
        for run in paragraph.runs:
            run_text = run.text.replace(headline, data)
            run.text = run_text

    # 用来替换word表格中的关键字内容,关键字都是excel表格的标题行
    mytables = document.tables
    for table in mytables:
        for row in table.rows:
            for cell in row.cells:
                cell_text = cell.text.replace(headline, data)
                cell.text = cell_text


xlsx = xlrd.open_workbook(r'D:\pycharm\learning\autowork\document\报告数据.xlsx')
table = xlsx.sheet_by_index(0)

for table_row in range(1, table.nrows):
    document = Document(r'D:\pycharm\learning\autowork\document\报告模板.docx')
    for table_col in range(0, table.ncols):
        text_chenge(str(table.cell(0, table_col).value), str(table.cell(table_row, table_col).value))
        # 将excel表格中的内容替换掉标题行,因为标题行即为报告模板中的关键字

    document.save(f'{str(table.cell(table_row, 0).value)} eSRVCC切换成功率低优化报告.docx')
    print("%s eSRVCC切换成功率低优化报告成功生成!" % str(table.cell_value(table_row, 0)))

你可能感兴趣的:(学习)