人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動(dòng)態(tài)

Python 自動(dòng)化處理Excel和Word實(shí)現(xiàn)自動(dòng)辦公

發(fā)布日期:2021-12-09 18:58 | 文章來源:gibhub

今天我來分享一些Python辦公自動(dòng)化的方法,歡迎收藏學(xué)習(xí),喜歡點(diǎn)贊支持,歡迎暢聊。

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)題,以及大量可以派上用場(chǎng)的其他功能。最重要的是,這個(gè)包使你能夠在 Excel 中迭代無數(shù)行和列,從而使你免于所有煩人的數(shù)字運(yùn)算和繪圖。

Python-docx

Python-docx 這個(gè)包之于 Word,就像 Openpyxl 之于 Excel。 如果你還沒有研究過他們的文檔,那么可能應(yīng)該看看。毫不夸張地說,自從我開始使用 Python 以來,Python-docx 是我使用過的最簡單、最不言自明的工具包之一。

它允許你通過插入文本、填寫表格并將圖像自動(dòng)渲染到報(bào)告中來自動(dòng)生成文檔,而無需任何開銷。

讓我們創(chuàng)建我們自己的自動(dòng)化管道。 繼續(xù)并啟動(dòng) Anaconda 并安裝以下軟件包:

pip install openpyxl
pip install python-docx

微軟 Excel 自動(dòng)化

我們加載一個(gè)已經(jīng)創(chuàng)建好的 Excel 工作簿(如下所示):

workbook = xl.load_workbook('Book1.xlsx')
sheet_1 = workbook['Sheet1']

我們將遍歷電子表格中的所有行,通過將電流乘以電壓來計(jì)算,插入功率值:

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

完成后,我們將使用計(jì)算的功率值生成一個(gè)折線圖,該折線圖將插入到指定的單元格中,如下所示:

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 報(bào)告中使用它。

首先,我們將聲明 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)

隨后,你可以遍歷電子表格中的所有圖表對(duì)象并將它們保存在指定位置,如下所示:

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 自動(dòng)化

現(xiàn)在我們已經(jīng)生成了我們的圖表圖像,我們必須創(chuàng)建一個(gè)模板文檔,它是一個(gè)普通的 Microsoft Word 文檔 (.docx),完全按照我們希望報(bào)告的外觀制定,包括字體、字體大小、格式和頁面結(jié)構(gòu) .

然后我們需要做的就是為我們的自動(dòng)化內(nèi)容創(chuàng)建占位符,即表格值和圖像,并使用如下所示的變量名稱聲明它們。

任何自動(dòng)化內(nèi)容都可以在一對(duì)雙大括號(hào) {{variable_name}} 內(nèi)聲明,包括文本和圖像。 對(duì)于表格,你需要?jiǎng)?chuàng)建一個(gè)包含所有列的模板行的表格,然后需要使用以下符號(hào)在上一行和下一行附加:

{%tr for item in variable_name %}

最后一行:

%tr endfor %}

在上圖中,變量名是

  • table_contents 用于存儲(chǔ)表格數(shù)據(jù)的 Python 字典
  • 字典鍵的索引(第一列)
  • 字典值的功率、電流和電壓(第二、第三和第四列)

然后我們將我們的模板文檔導(dǎo)入 Python 并創(chuàng)建一個(gè)字典來存儲(chǔ)我們表的值:

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)建另一個(gè)字典來實(shí)例化模板文檔中聲明的所有占位符變量:

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)報(bào)告:

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

總結(jié)

就這樣,自動(dòng)生成的 Microsoft Word 報(bào)告包含數(shù)字和在 Microsoft Excel 中創(chuàng)建的圖表。有了它,你就擁有了一個(gè)完全自動(dò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 的更多信息,請(qǐng)加入技術(shù)交流群。

技術(shù)交流

歡迎轉(zhuǎn)載、收藏、有所收獲點(diǎn)贊支持一下!

到此這篇關(guān)于Python 自動(dòng)化處理Excel和Word實(shí)現(xiàn)自動(dòng)辦公的文章就介紹到這了,更多相關(guān)Python 自動(dòng)化辦公內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!

版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實(shí)時(shí)開通

自選配置、實(shí)時(shí)開通

免備案

全球線路精選!

全天候客戶服務(wù)

7x24全年不間斷在線

專屬顧問服務(wù)

1對(duì)1客戶咨詢顧問

在線
客服

在線客服:7*24小時(shí)在線

客服
熱線

400-630-3752
7*24小時(shí)客服服務(wù)熱線

關(guān)注
微信

關(guān)注官方微信
頂部