Python 自動化處理Excel和Word實現(xiàn)自動辦公
今天我來分享一些Python辦公自動化的方法,歡迎收藏學習,喜歡點贊支持,歡迎暢聊。
Openpyxl
Openpyxl 可以說是 Python 中最通用的工具模塊了,它使與 Excel 交互pip install openpyxl
pip install python-docx簡直就像在公園里漫步一樣。 有了它,你就可以讀寫所有當前和傳統(tǒng)的 excel 格式,即 xlsx 和 xls。
Openpyxl 允許填充行和列、執(zhí)行公式、創(chuàng)建 2D 和 3D 圖表、標記軸和標題,以及大量可以派上用場的其他功能。最重要的是,這個包使你能夠在 Excel 中迭代無數(shù)行和列,從而使你免于所有煩人的數(shù)字運算和繪圖。
Python-docx
Python-docx 這個包之于 Word,就像 Openpyxl 之于 Excel。 如果你還沒有研究過他們的文檔,那么可能應該看看。毫不夸張地說,自從我開始使用 Python 以來,Python-docx 是我使用過的最簡單、最不言自明的工具包之一。
它允許你通過插入文本、填寫表格并將圖像自動渲染到報告中來自動生成文檔,而無需任何開銷。
讓我們創(chuàng)建我們自己的自動化管道。 繼續(xù)并啟動 Anaconda 并安裝以下軟件包:
pip install openpyxl pip install python-docx
微軟 Excel 自動化
我們加載一個已經(jīng)創(chuàng)建好的 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')

提取圖表
現(xiàn)在我們已經(jīng)生成了圖表,我們需要將其提取為圖像,以便我們可以在 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 自動化
現(xiàn)在我們已經(jīng)生成了我們的圖表圖像,我們必須創(chuàng)建一個模板文檔,它是一個普通的 Microsoft Word 文檔 (.docx),完全按照我們希望報告的外觀制定,包括字體、字體大小、格式和頁面結構 .
然后我們需要做的就是為我們的自動化內(nèi)容創(chuàng)建占位符,即表格值和圖像,并使用如下所示的變量名稱聲明它們。

任何自動化內(nèi)容都可以在一對雙大括號 {{variable_name}} 內(nèi)聲明,包括文本和圖像。 對于表格,你需要創(chuàng)建一個包含所有列的模板行的表格,然后需要使用以下符號在上一行和下一行附加:
{%tr for item in variable_name %}
最后一行:
%tr endfor %}
在上圖中,變量名是
- table_contents 用于存儲表格數(shù)據(jù)的 Python 字典
- 字典鍵的索引(第一列)
- 字典值的功率、電流和電壓(第二、第三和第四列)
然后我們將我們的模板文檔導入 Python 并創(chuàng)建一個字典來存儲我們表的值:
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 生成的圖表圖像,并將創(chuàng)建另一個字典來實例化模板文檔中聲明的所有占位符變量:
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
}
最后,我們將使用我們的值表和圖表圖像呈現(xiàn)報告:
template.render(context)
template.save('Automated_report.docx')
總結
就這樣,自動生成的 Microsoft Word 報告包含數(shù)字和在 Microsoft Excel 中創(chuàng)建的圖表。有了它,你就擁有了一個完全自動化的管道,可用于創(chuàng)建可能需要的盡可能多的表格、圖表和文檔。

源碼如下
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')
如果你想了解有關數(shù)據(jù)可視化和 Python 的更多信息,請加入技術交流群。
技術交流
歡迎轉(zhuǎn)載、收藏、有所收獲點贊支持一下!

到此這篇關于Python 自動化處理Excel和Word實現(xiàn)自動辦公的文章就介紹到這了,更多相關Python 自動化辦公內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
用Python實現(xiàn)一個簡單的能夠發(fā)送帶附件的郵件程序的教程
這篇文章主要介紹了用Python實現(xiàn)一個簡單的能夠發(fā)送帶附件的郵件程序的教程,用MIMEApplication模塊來發(fā)送各種類型的文件,需要的朋友可以參考下2015-04-04

