Python 自動化處理Excel和Word實現(xiàn)自動辦公
今天我來分享一些Python辦公自動化的方法,歡迎收藏學(xué)習(xí),喜歡點贊支持,歡迎暢聊。
Openpyxl
Openpyxl 可以說是 Python 中最通用的工具模塊了,它使與 Excel 交互pip install openpyxl
pip install python-docx簡直就像在公園里漫步一樣。 有了它,你就可以讀寫所有當(dāng)前和傳統(tǒng)的 excel 格式,即 xlsx 和 xls。
Openpyxl 允許填充行和列、執(zhí)行公式、創(chuàng)建 2D 和 3D 圖表、標(biāo)記軸和標(biāo)題,以及大量可以派上用場的其他功能。最重要的是,這個包使你能夠在 Excel 中迭代無數(shù)行和列,從而使你免于所有煩人的數(shù)字運算和繪圖。
Python-docx
Python-docx 這個包之于 Word,就像 Openpyxl 之于 Excel。 如果你還沒有研究過他們的文檔,那么可能應(yīng)該看看。毫不夸張地說,自從我開始使用 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 文件的確切位置以及應(yīng)保存輸出圖表圖像的位置:
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),完全按照我們希望報告的外觀制定,包括字體、字體大小、格式和頁面結(jié)構(gòu) .
然后我們需要做的就是為我們的自動化內(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 字典
- 字典鍵的索引(第一列)
- 字典值的功率、電流和電壓(第二、第三和第四列)
然后我們將我們的模板文檔導(dǎo)入 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
})
接下來,我們將導(dǎo)入之前由 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')
總結(jié)
就這樣,自動生成的 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')
如果你想了解有關(guān)數(shù)據(jù)可視化和 Python 的更多信息,請加入技術(shù)交流群。
技術(shù)交流
歡迎轉(zhuǎn)載、收藏、有所收獲點贊支持一下!

到此這篇關(guān)于Python 自動化處理Excel和Word實現(xiàn)自動辦公的文章就介紹到這了,更多相關(guān)Python 自動化辦公內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python預(yù)測2020高考分數(shù)和錄取情況
這篇文章主要介紹了Python預(yù)測2020高考分數(shù)和錄取情況可能是這樣,本文通過示例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
Python基本結(jié)構(gòu)之判斷語句的用法詳解
在程序的設(shè)計當(dāng)中,代碼并不是逐步按照順序進行執(zhí)行的,在運行到某一行代碼當(dāng)中,需要停下進行判斷接下來將要運行到那一個分支代碼,這種判斷就代表的是分支結(jié)構(gòu)。分支結(jié)構(gòu)是可以使用?if?語句來進行判斷的,而我們本篇博客講的也是?if?語句,需要的可以了解一下2022-07-07
Python實現(xiàn)視頻轉(zhuǎn)換為字符畫詳解
這篇文章主要介紹了如何通過Python實現(xiàn)讀取視頻并將其轉(zhuǎn)換為字符畫的示例代碼,文中講解詳細,對我們的學(xué)習(xí)和工作有一點的價值,感興趣的小伙伴可以了解一下2021-12-12
解決python多線程報錯:AttributeError: Can''t pickle local object問題
這篇文章主要介紹了解決python多線程報錯:AttributeError: Can't pickle local object問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
一文帶你理解Python中import機制與importlib的妙用
在Python編程的世界里,import語句是開發(fā)者最常用的工具之一,它就像一把鑰匙,打開了通往各種功能和庫的大門,下面就跟隨小編一起來學(xué)習(xí)一下import機制的具體使用吧2025-01-01
tensorflow之tf.record實現(xiàn)存浮點數(shù)數(shù)組
今天小編就為大家分享一篇tensorflow之tf.record實現(xiàn)存浮點數(shù)數(shù)組,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02

