今天我来分享一些python办公自动化的方法,欢迎收藏学习,喜欢点赞支持,欢迎畅聊。

openpyxl

openpyxl 可以说是 python 中最通用的工具模块了,它使与 excel 交互pip install openpyxl
pip install python-docx简直就像在公园里漫步一样。 有了它,你就可以读写所有当前和传统的 excel 格式,即 xlsx 和 xls。

openpyxl 允许填充行和列、执行公式、创建 2d 和 3d 图表、标记轴和标题,以及大量可以派上用场的其他功能。最重要的是,这个包使你能够在 excel 中迭代无数行和列,从而使你免于所有烦人的数字运算和绘图。

python-docx

python-docx 这个包之于 word,就像 openpyxl 之于 excel。 如果你还没有研究过他们的文档,那么可能应该看看。毫不夸张地说,自从我开始使用 python 以来,python-docx 是我使用过的最简单、最不言自明的工具包之一。

它允许你通过插入文本、填写表格并将图像自动渲染到报告中来自动生成文档,而无需任何开销。

让我们创建我们自己的自动化管道。 继续并启动 anaconda 并安装以下软件包:

pip install openpyxl
pip install python-docx

微软 excel 自动化

我们加载一个已经创建好的 excel 工作簿(如下所示):

workbook = xl.load_workbook('book1.xlsx')
sheet_1 = workbook['sheet1']

我们将遍历电子表格中的所有行,通过将电流乘以电压来计算,插入功率值:

for row in range(2, sheet_1.max_row + 1):
    current = sheet_1.cell(row, 2)
    voltage = sheet_1.cell(row, 3)
    power = float(current.value) * float(voltage.value)
    power_cell = sheet_1.cell(row, 1)
    power_cell.value = power

完成后,我们将使用计算的功率值生成一个折线图,该折线图将插入到指定的单元格中,如下所示:

values = reference(sheet_1, min_row = 2, max_row = sheet_1.max_row, min_col = 1, max_col = 1)
chart = linechart()
chart.y_axis.title = 'power'
chart.x_axis.title = 'index'
chart.add_data(values)
sheet_1.add_chart(chart, 'e2') 
workbook.save('book1.xlsx')

提取图表

现在我们已经生成了图表,我们需要将其提取为图像,以便我们可以在 word 报告中使用它。

首先,我们将声明 excel 文件的确切位置以及应保存输出图表图像的位置:

input_file = "c:/users/.../book1.xlsx"
output_image = "c:/users/.../chart.png"

然后使用以下方法访问电子表格:

operation = win32com.client.dispatch("excel.application")
operation.visible = 0
operation.displayalerts = 0
workbook_2 = operation.workbooks.open(input_file)
sheet_2 = operation.sheets(1)

随后,你可以遍历电子表格中的所有图表对象并将它们保存在指定位置,如下所示:

for x, chart in enumerate(sheet_2.shapes):
    chart.copy()
    image = imagegrab.grabclipboard()
    image.save(output_image, 'png')
    pass
workbook_2.close(true)
operation.quit()

微软 word 自动化

现在我们已经生成了我们的图表图像,我们必须创建一个模板文档,它是一个普通的 microsoft word 文档 (.docx),完全按照我们希望报告的外观制定,包括字体、字体大小、格式和页面结构 .

然后我们需要做的就是为我们的自动化内容创建占位符,即表格值和图像,并使用如下所示的变量名称声明它们。

任何自动化内容都可以在一对双大括号 { {variable_name}} 内声明,包括文本和图像。 对于表格,你需要创建一个包含所有列的模板行的表格,然后需要使用以下符号在上一行和下一行附加:

{%tr for item in variable_name %}

最后一行:

%tr endfor %}

在上图中,变量名是

  • table_contents 用于存储表格数据的 python 字典
  • 字典键的索引(第一列)
  • 字典值的功率、电流和电压(第二、第三和第四列)

然后我们将我们的模板文档导入 python 并创建一个字典来存储我们表的值:

template = docxtemplate('template.docx')
table_contents = []
for i in range(2, sheet_1.max_row + 1):
    table_contents.append({
        'index': i-1,
        'power': sheet_1.cell(i, 1).value,
        'current': sheet_1.cell(i, 2).value,
        'voltage': sheet_1.cell(i, 3).value
        })

接下来,我们将导入之前由 excel 生成的图表图像,并将创建另一个字典来实例化模板文档中声明的所有占位符变量:

image = inlineimage(template,'chart.png',cm(10))
context = {
    'title': 'automated report',
    'day': datetime.datetime.now().strftime('%d'),
    'month': datetime.datetime.now().strftime('%b'),
    'year': datetime.datetime.now().strftime('%y'),
    'table_contents': table_contents,
    'image': image
    }

最后,我们将使用我们的值表和图表图像呈现报告:

template.render(context)
template.save('automated_report.docx')

总结

就这样,自动生成的 microsoft word 报告包含数字和在 microsoft excel 中创建的图表。有了它,你就拥有了一个完全自动化的管道,可用于创建可能需要的尽可能多的表格、图表和文档。

源码如下

import openpyxl as xl
from openpyxl.chart import linechart, reference

import win32com.client
import pil
from pil import imagegrab, image
import os
import sys

from docx.shared import cm
from docxtpl import docxtemplate, inlineimage
from docx.shared import cm, inches, mm, emu
import random
import datetime
import matplotlib.pyplot as plt


######## generate automated excel workbook ########

workbook = xl.load_workbook('book1.xlsx')
sheet_1 = workbook['sheet1']
  
for row in range(2, sheet_1.max_row + 1):
    current = sheet_1.cell(row, 2)
    voltage = sheet_1.cell(row, 3)
    power = float(current.value) * float(voltage.value)
    power_cell = sheet_1.cell(row, 1)
    power_cell.value = power
  
values = reference(sheet_1, min_row = 2, max_row = sheet_1.max_row, min_col = 1, max_col = 1)
chart = linechart()
chart.y_axis.title = 'power'
chart.x_axis.title = 'index'
chart.add_data(values)
sheet_1.add_chart(chart, 'e2')
  
workbook.save('book1.xlsx')


######## extract chart image from excel workbook ########

input_file = "c:/users/.../book1.xlsx"
output_image = "c:/users/.../chart.png"

operation = win32com.client.dispatch("excel.application")
operation.visible = 0
operation.displayalerts = 0
    
workbook_2 = operation.workbooks.open(input_file)
sheet_2 = operation.sheets(1)
    
for x, chart in enumerate(sheet_2.shapes):
    chart.copy()
    image = imagegrab.grabclipboard()
    image.save(output_image, 'png')
    pass

workbook_2.close(true)
operation.quit()


######## generating automated word document ########

template = docxtemplate('template.docx')

#generate list of random values
table_contents = []

for i in range(2, sheet_1.max_row + 1):
    
    table_contents.append({
        'index': i-1,
        'power': sheet_1.cell(i, 1).value,
        'current': sheet_1.cell(i, 2).value,
        'voltage': sheet_1.cell(i, 3).value
        })

#import saved figure
image = inlineimage(template,'chart.png',cm(10))

#declare template variables
context = {
    'title': 'automated report',
    'day': datetime.datetime.now().strftime('%d'),
    'month': datetime.datetime.now().strftime('%b'),
    'year': datetime.datetime.now().strftime('%y'),
    'table_contents': table_contents,
    'image': image
    }

#render automated report
template.render(context)
template.save('automated_report.docx')

如果你想了解有关数据可视化和 python 的更多信息,请加入技术交流群。

技术交流

欢迎转载、收藏、有所收获点赞支持一下!

到此这篇关于python 自动化处理excel和word实现自动办公的文章就介绍到这了,更多相关python 自动化办公内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!