那曲檬骨新材料有限公司

0
  • 聊天消息
  • 系統(tǒng)消息
  • 評(píng)論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會(huì)員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識(shí)你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

如何在環(huán)境安裝使用Python操作word

Android編程精選 ? 來源:CSDN博客 ? 作者:超級(jí)大洋蔥806 ? 2021-09-05 15:13 ? 次閱讀

作者丨超級(jí)大洋蔥806

https://tangxing.blog.csdn.net/article/details/108418066

環(huán)境安裝使用Python操作word大部分情況都是寫操作,也有少許情況會(huì)用到讀操作,在本次教程中都會(huì)進(jìn)行講解,本次課程主要用到以下4個(gè)庫(kù),請(qǐng)大家提前安裝。

升級(jí)pip(便于安裝最新庫(kù))

python -m pip install -U pip setuptools

python-docx(我們大部分操作都是使用此庫(kù))

安裝方法:

pip install python-docx

使用方法:

from docx import Document

from docx.shared import Inches

官方文檔:

https://python-docx.readthedocs.io/en/latest/index.html

win32com(主要用作doc轉(zhuǎn)docx格式轉(zhuǎn)換用)

安裝方法:

pip install pypiwin32

使用方法:

import win32com

from win32com.client import Dispatch, constants

官方文檔:

https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word?view=word-pia

mailmerge(用作按照模板生成大量同類型文檔)

安裝方法:

pip install docx-mailmerge

使用方法:

from mailmerge import MailMerge

官方文檔:

https://pypi.org/project/docx-mailmerge/

matplotlib(Python 的繪圖庫(kù),本期簡(jiǎn)單講解,后期會(huì)有專門的課程)

安裝方法:

pip install matplotlib

使用方法:

import matplotlib.pyplot as plt

官方文檔:

https://matplotlib.org/3.2.2/tutorials/introductory/sample_plots.html

Python-docx 新建文檔示例代碼1:

from docx import Document

document = Document()

document.save(‘new.docx’)

示例代碼 0.1 Python-docx新建文檔.py:

from docx import Document

def GenerateNewWord(filename):

document = Document()

document.save(filename)

if __name__ == “__main__”:

print(“大家好!我們今天開始學(xué)習(xí)word文檔自動(dòng)化”)

print(“我們先來直接生成一個(gè)名為‘new.docx’的文檔”)

document = Document()

document.save(‘new.docx’)

print(“沒錯(cuò),里面什么都沒有”)

# 我是華麗的分隔符

print(“我們使用函數(shù)生成一個(gè)word文檔試試”)

newname = ‘使用函數(shù)生成的文檔.docx’

GenerateNewWord(newname)

Python-docx 編輯已存在文檔我們很多時(shí)候需要在已存在的word文檔上添加自己的內(nèi)容,那么我們趕緊看看應(yīng)該怎樣操作吧~

舊文檔:

示例代碼:

from docx import Document

document = Document(‘exist.docx’)

document.save(‘new.docx’)

也許你會(huì)說,沒有沒搞錯(cuò),就這三句話?是的,就這三句,你就完成了舊文檔的復(fù)制,如果你想修改,直接添加內(nèi)容就行了呢!

win32com 將 doc 轉(zhuǎn)為 docx舊文檔:

示例代碼:

import os

from win32com import client as wc

def TransDocToDocx(oldDocName,newDocxName):

print(“我是 TransDocToDocx 函數(shù)”)

# 打開word應(yīng)用程序

word = wc.Dispatch(‘Word.Application’)

# 打開 舊word 文件

doc = word.Documents.Open(oldDocName)

# 保存為 新word 文件,其中參數(shù) 12 表示的是docx文件

doc.SaveAs(newDocxName, 12)

# 關(guān)閉word文檔

doc.Close()

word.Quit()

print(“生成完畢!”)

if __name__ == “__main__”:

# 獲取當(dāng)前目錄完整路徑

currentPath = os.getcwd()

print(“當(dāng)前路徑為:”,currentPath)

# 獲取 舊doc格式word文件絕對(duì)路徑名

docName = os.path.join(currentPath,‘舊doc格式文檔.doc’)

print(“docFilePath = ”, docName)

# 設(shè)置新docx格式文檔文件名

docxName = os.path.join(currentPath,‘新生成docx格式文檔.docx’)

TransDocToDocx(docName,docxName)

win32com 操作 word打開新的word文檔并添加內(nèi)容

示例代碼:

import win32com

from win32com.client import Dispatch, constants

import os

# 創(chuàng)建新的word文檔def funOpenNewFile():

word = Dispatch(‘Word.Application’)

# 或者使用下面的方法,使用啟動(dòng)獨(dú)立的進(jìn)程:

# word = DispatchEx(‘Word.Application’)

# 如果不聲明以下屬性,運(yùn)行的時(shí)候會(huì)顯示的打開word

word.Visible = 1 # 0:后臺(tái)運(yùn)行 1:前臺(tái)運(yùn)行(可見)

word.DisplayAlerts = 0 # 不顯示,不警告

# 創(chuàng)建新的word文檔

doc = word.Documents.Add()

# 在文檔開頭添加內(nèi)容

myRange1 = doc.Range(0, 0)

myRange1.InsertBefore(‘Hello word

’)

# 在文檔末尾添加內(nèi)容

myRange2 = doc.Range()

myRange2.InsertAfter(‘Bye word

’)

# 在文檔i指定位置添加內(nèi)容

i = 0

myRange3 = doc.Range(0, i)

myRange3.InsertAfter(“what‘s up, bro?

”)

# doc.Save() # 保存

doc.SaveAs(os.getcwd() + “\funOpenNewFile.docx”) # 另存為

doc.Close() # 關(guān)閉 word 文檔

word.Quit() # 關(guān)閉 officeif __name__ == ’__main__‘:

print(“當(dāng)前文件路徑名:”,os.getcwd())

print(“調(diào)用funOpenNewFile()”)

funOpenNewFile()

打開已存在word文檔并添加內(nèi)容

前提條件:

示例代碼:

import win32com

from win32com.client import Dispatch, constants

import os

# 打開已存在的word文件def funOpenExistFile():

word = Dispatch(’Word.Application‘)

# 或者使用下面的方法,使用啟動(dòng)獨(dú)立的進(jìn)程:

# word = DispatchEx(’Word.Application‘)

# 如果不聲明以下屬性,運(yùn)行的時(shí)候會(huì)顯示的打開word

word.Visible = 1 # 0:后臺(tái)運(yùn)行 1:前臺(tái)運(yùn)行(可見)

word.DisplayAlerts = 0 # 不顯示,不警告

doc = word.Documents.Open(os.getcwd() + “\3.1 win32com測(cè)試.docx”) # 打開一個(gè)已有的word文檔

# 在文檔開頭添加內(nèi)容

myRange1 = doc.Range(0, 0)

myRange1.InsertBefore(’Hello word

‘)

# 在文檔末尾添加內(nèi)容

myRange2 = doc.Range()

myRange2.InsertAfter(’Bye word

‘)

# 在文檔i指定位置添加內(nèi)容

i = 0

myRange3 = doc.Range(0, i)

myRange3.InsertAfter(“what’s up, bro?

”)

# doc.Save() # 保存

doc.SaveAs(os.getcwd() + “\funOpenExistFile.docx”) # 另存為

doc.Close() # 關(guān)閉 word 文檔

word.Quit() # 關(guān)閉 officeif __name__ == ‘__main__’:

print(“當(dāng)前文件路徑名:”,os.getcwd())

print(“調(diào)用funOpenExistFile()”)

funOpenExistFile()

轉(zhuǎn)換word為pdf

示例代碼:

import win32com

from win32com.client import Dispatch, constants

import os

# 生成Pdf文件def funGeneratePDF():

word = Dispatch(“Word.Application”)

word.Visible = 0 # 后臺(tái)運(yùn)行,不顯示

word.DisplayAlerts = 0 # 不警告

doc = word.Documents.Open(os.getcwd() + “\3.3 win32com轉(zhuǎn)換word為pdf等格式.docx”) # 打開一個(gè)已有的word文檔

doc.SaveAs(os.getcwd() + “\3.3 win32com轉(zhuǎn)換word為pdf等格式.pdf”, 17) # txt=4, html=10, docx=16, pdf=17

doc.Close()

word.Quit()

if __name__ == ‘__main__’:

funGeneratePDF()

Python-docx 操作 word官方文檔:(最權(quán)威指南,沒有之一)

https://python-docx.readthedocs.io/en/latest/

Python-docx官方例程

前提條件:

示例代碼:

from docx import Document

from docx.shared import Inches

document = Document()

document.add_heading(‘Document Title’, 0)

p = document.add_paragraph(‘A plain paragraph having some ’)

p.add_run(‘bold’).bold = True

p.add_run(‘ and some ’)

p.add_run(‘italic.’).italic = True

document.add_heading(‘Heading, level 1’, level=1)

document.add_paragraph(‘Intense quote’, style=‘Intense Quote’)

document.add_paragraph(

‘first item in unordered list’, style=‘List Bullet’

document.add_paragraph(

‘first item in ordered list’, style=‘List Number’

document.add_picture(‘countrygarden.png’, width=Inches(1.25))

records = (

(3, ‘101’, ‘Spam’),

(7, ‘422’, ‘Eggs’),

(4, ‘631’, ‘Spam, spam, eggs, and spam’)

table = document.add_table(rows=1, cols=3)

hdr_cells = table.rows[0].cells

hdr_cells[0].text = ‘Qty’

hdr_cells[1].text = ‘Id’

hdr_cells[2].text = ‘Desc’for qty, id, desc in records:

row_cells = table.add_row().cells

row_cells[0].text = str(qty)

row_cells[1].text = id

row_cells[2].text = desc

document.add_page_break()

document.save(‘4.1 Python-docx官方例程.docx’)

最終效果:

Python-docx官方例程解析

導(dǎo)入庫(kù)操作

from docx import Document

導(dǎo)入英寸單位操作(可用于指定圖片大小、表格寬高等)

from docx.shared import Inches

新建一個(gè)文檔

document = Document()

加載舊文檔(用于修改或添加內(nèi)容)

document = Document(‘exist.docx’)

添加標(biāo)題段落

document.add_heading(‘Document Title’, 0)

7322cb68-0d7c-11ec-8fb8-12bb97331649.png

添加段落操作

段落在 Word 中是基本內(nèi)容。它們用于正文文本,也用于標(biāo)題和項(xiàng)目列表(如項(xiàng)目符號(hào))。

p = document.add_paragraph(‘A plain paragraph having some ’)

在指定段落上添加內(nèi)容

p.add_run(‘bold’).bold = True # 添加粗體文字

p.add_run(‘ and some ’) # 添加默認(rèn)格式文字

p.add_run(‘italic.’).italic = True # 添加斜體文字

添加標(biāo)題操作

等級(jí)1-9 也就是標(biāo)題1-標(biāo)題9,我們可以在舊文檔中將標(biāo)題格式設(shè)置好,使用Python-docx打開舊文檔,再添加相應(yīng)等級(jí)標(biāo)題即可。

document.add_heading(‘Heading, level 1’, level=1)

添加指定樣式段落

樣式詳情:

https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html#understanding-styles

document.add_paragraph(‘Intense quote’, style=‘Intense Quote’)

# 以下兩句的含義等同于上面一句

p = document.add_paragraph(‘Intense quote’)

p.style = ‘Intense Quote’

添加無(wú)序列表操作

document.add_paragraph( ‘first item in unordered list’, style=‘List Bullet’)

添加有序列表操作

document.add_paragraph( ‘first item in ordered list’, style=‘List Number’)

73500452-0d7c-11ec-8fb8-12bb97331649.png

添加圖片操作

第一個(gè)參數(shù)為圖片路徑,需要正確無(wú)誤

第二個(gè)參數(shù)為圖片大小,單位英寸

document.add_picture(‘countrygarden.png’, width=Inches(1.25))

新建表格操作

table = document.add_table(rows=1, cols=3)

填充標(biāo)題行操作

hdr_cells = table.rows[0].cells

hdr_cells[0].text = ‘Qty’

hdr_cells[1].text = ‘Id’

hdr_cells[2].text = ‘Desc’

為每組內(nèi)容添加數(shù)據(jù)行并填充

for qty, id, desc in records:

row_cells = table.add_row().cells

row_cells[0].text = str(qty)

row_cells[1].text = id

row_cells[2].text = desc

設(shè)置標(biāo)題樣式操作

table.style = ‘LightShading-Accent1’

7373d3e6-0d7c-11ec-8fb8-12bb97331649.png

添加分頁(yè)符操作

document.add_page_break()

保存當(dāng)前文檔操作

document.save(‘4.1 Python-docx官方例程.docx’)

Python-docx 表格樣式設(shè)置

表格樣式設(shè)置代碼:

from docx import *

document = Document()

table = document.add_table(3, 3, style=“Medium Grid 1 Accent 1”)

heading_cells = table.rows[0].cells

heading_cells[0].text = ‘第一列內(nèi)容’

heading_cells[1].text = ‘第二列內(nèi)容’

heading_cells[2].text = ‘第三列內(nèi)容’

document.save(“demo.docx”)

遍歷所有樣式:

from docx.enum.style import WD_STYLE_TYPE

from docx import Document

document = Document()

styles = document.styles

# 生成所有表樣式for s in styles:

if s.type == WD_STYLE_TYPE.TABLE:

document.add_paragraph(“表格樣式 : ” + s.name)

table = document.add_table(3, 3, style=s)

heading_cells = table.rows[0].cells

heading_cells[0].text = ‘第一列內(nèi)容’

heading_cells[1].text = ‘第二列內(nèi)容’

heading_cells[2].text = ‘第三列內(nèi)容’

document.add_paragraph(“

”)

document.save(‘4.3 所有表格樣式.docx’)

效果如下(大家按照喜歡的樣式添加即可):

docx&matplotlib 自動(dòng)生成數(shù)據(jù)分析報(bào)告最終效果

數(shù)據(jù)獲取

我們這里使用xlrd作為數(shù)據(jù)獲取所使用的庫(kù),簡(jiǎn)單回顧一下:

import xlrd

xlsx = xlrd.open_workbook(‘。/3_1 xlrd 讀取 操作練習(xí).xlsx’)

# 通過sheet名查找:xlsx.sheet_by_name(“sheet1”)# 通過索引查找:xlsx.sheet_by_index(3)

table = xlsx.sheet_by_index(0)

# 獲取單個(gè)表格值 (2,1)表示獲取第3行第2列單元格的值

value = table.cell_value(2, 1)

print(“第3行2列值為”,value)

# 獲取表格行數(shù)

nrows = table.nrows

print(“表格一共有”,nrows,“行”)

# 獲取第4列所有值(列表生成式)

name_list = [str(table.cell_value(i, 3)) for i in range(1, nrows)]

print(“第4列所有的值:”,name_list)

表格內(nèi)容:

編寫數(shù)據(jù)獲取代碼:

我們這里只獲取用戶姓名和,分?jǐn)?shù),并將它們保存到列表中,看代碼。

# 獲取學(xué)習(xí)成績(jī)信息def GetExcelInfo():

print(“開始獲取表格內(nèi)容信息”)

# 打開指定文檔

xlsx = xlrd.open_workbook(‘學(xué)生成績(jī)表格.xlsx’)

# 獲取sheet

sheet = xlsx.sheet_by_index(0)

# 獲取表格行數(shù)

nrows = sheet.nrows

print(“一共 ”,nrows,“ 行數(shù)據(jù)”)

# 獲取第2列,和第4列 所有值(列表生成式),從第2行開始獲取

nameList = [str(sheet.cell_value(i, 1)) for i in range(1, nrows)]

scoreList = [int(sheet.cell_value(i, 3)) for i in range(1, nrows)]

# 返回名字列表和分?jǐn)?shù)列表

return nameList,scoreList

獲取結(jié)果:

73c1f06c-0d7c-11ec-8fb8-12bb97331649.png

柱狀圖生成

我們先將獲取的姓名和成績(jī)使用 字典 數(shù)據(jù)結(jié)構(gòu)關(guān)聯(lián)起來,再對(duì)其排序:

# 將名字和分?jǐn)?shù)列表合并成字典(將學(xué)生姓名和分?jǐn)?shù)關(guān)聯(lián)起來)

scoreDictionary = dict(zip(nameList, scoreList))

print(“dictionary:”,scoreDictionary)

# 對(duì)字典進(jìn)行值排序,高分在前,reverse=True 代表降序排列

scoreOrder = sorted(scoreDictionary.items(), key=lambda x: x[1], reverse=True)

print(“scoreOrder”,scoreOrder)

# 合成的字典

dictionary: {‘Dillon Miller’: 41, ‘Laura Robinson’: 48, ‘Gabrilla Rogers’: 28, ‘Carlos Chen’: 54, ‘Leonard Humphrey’: 44, ‘John Hall’: 63, ‘Miranda Nelson’: 74, ‘Jessica Morgan’: 34, ‘April Lawrence’: 67, ‘Cindy Brown’: 52, ‘Cassandra Fernan’: 29, ‘April Crawford’: 91, ‘Jennifer Arias’: 61, ‘Philip Walsh’: 58, ‘Christina Hill P’: 14, ‘Justin Dunlap’: 56, ‘Brian Lynch’: 84, ‘Michael Brown’: 68}

# 排序后,再次轉(zhuǎn)換成列表

scoreOrder [(‘April Crawford’, 91), (‘Brian Lynch’, 84), (‘Miranda Nelson’, 74), (‘Michael Brown’, 68), (‘April Lawrence’, 67), (‘John Hall’, 63), (‘Jennifer Arias’, 61), (‘Philip Walsh’, 58), (‘Justin Dunlap’, 56), (‘Carlos Chen’, 54), (‘Cindy Brown’, 52), (‘Laura Robinson’, 48), (‘Leonard Humphrey’, 44), (‘Dillon Miller’, 41), (‘Jessica Morgan’, 34), (‘Cassandra Fernan’, 29), (‘Gabrilla Rogers’, 28), (‘Christina Hill P’, 14)]

使用 matplotlib 生成柱狀圖:

# 生成學(xué)生成績(jī)柱狀圖(使用matplotlib)# 會(huì)生成一張名為“studentScore.jpg”的圖片def GenerateScorePic(scoreList):

# 解析成績(jī)列表,生成橫縱坐標(biāo)列表

xNameList = [str(studentInfo[0]) for studentInfo in scoreList]

yScoreList = [int(studentInfo[1]) for studentInfo in scoreList]

print(“xNameList”,xNameList)

print(“yScoreList”,yScoreList)

# 設(shè)置字體格式

matplotlib.rcParams[‘font.sans-serif’] = [‘SimHei’] # 用黑體顯示中文

# 設(shè)置繪圖尺寸

plt.figure(figsize=(10,5))

# 繪制圖像

plt.bar(x=xNameList, height=yScoreList, label=‘學(xué)生成績(jī)’, color=‘steelblue’, alpha=0.8)

# 在柱狀圖上顯示具體數(shù)值, ha參數(shù)控制水平對(duì)齊方式, va控制垂直對(duì)齊方式

for x1, yy in scoreList:

plt.text(x1, yy + 1, str(yy), ha=‘center’, va=‘bottom’, fontsize=16, rotation=0)

# 設(shè)置標(biāo)題

plt.title(“學(xué)生成績(jī)柱狀圖”)

# 為兩條坐標(biāo)軸設(shè)置名稱

plt.xlabel(“學(xué)生姓名”)

plt.ylabel(“學(xué)生成績(jī)”)

# 顯示圖例

plt.legend()

# 坐標(biāo)軸旋轉(zhuǎn)

plt.xticks(rotation=90)

# 設(shè)置底部比例,防止橫坐標(biāo)顯示不全

plt.gcf().subplots_adjust(bottom=0.25)

# 保存為圖片

plt.savefig(“studentScore.jpg”)

# 直接顯示

plt.show()

生成最終報(bào)告

代碼如下:

# 開始生成報(bào)告def GenerateScoreReport(scoreOrder,picPath):

# 新建一個(gè)文檔

document = Document()

# 設(shè)置標(biāo)題

document.add_heading(‘?dāng)?shù)據(jù)分析報(bào)告’, 0)

# 添加第一名的信息

p1 = document.add_paragraph(“分?jǐn)?shù)排在第一的學(xué)生姓名為: ”)

p1.add_run(scoreOrder[0][0]).bold = True

p1.add_run(“ 分?jǐn)?shù)為: ”)

p1.add_run(str(scoreOrder[0][1])).italic = True

# 添加總體情況信息

p2 = document.add_paragraph(“共有: ”)

p2.add_run(str(len(scoreOrder))).bold = True

p2.add_run(“ 名學(xué)生參加了考試,學(xué)生考試的總體情況: ”)

# 添加考試情況表格

table = document.add_table(rows=1, cols=2)

table.style = ‘Medium Grid 1 Accent 1’

hdr_cells = table.rows[0].cells

hdr_cells[0].text = ‘學(xué)生姓名’

hdr_cells[1].text = ‘學(xué)生分?jǐn)?shù)’

for studentName,studentScore in scoreOrder:

row_cells = table.add_row().cells

row_cells[0].text = studentName

row_cells[1].text = str(studentScore)

# 添加學(xué)生成績(jī)柱狀圖

document.add_picture(picPath, width=Inches(6))

document.save(‘學(xué)生成績(jī)報(bào)告.docx’)

完整代碼

import xlrd

import matplotlib

import matplotlib.pyplot as plt

from docx import Document

from docx.shared import Inches

# 獲取學(xué)習(xí)成績(jī)信息def GetExcelInfo():

print(“開始獲取表格內(nèi)容信息”)

# 打開指定文檔

xlsx = xlrd.open_workbook(‘學(xué)生成績(jī)表格.xlsx’)

# 獲取sheet

sheet = xlsx.sheet_by_index(0)

# 獲取表格行數(shù)

nrows = sheet.nrows

print(“一共 ”,nrows,“ 行數(shù)據(jù)”)

# 獲取第2列,和第4列 所有值(列表生成式),從第2行開始獲取

nameList = [str(sheet.cell_value(i, 1)) for i in range(1, nrows)]

scoreList = [int(sheet.cell_value(i, 3)) for i in range(1, nrows)]

# 返回名字列表和分?jǐn)?shù)列表

return nameList,scoreList

# 生成學(xué)生成績(jī)柱狀圖(使用matplotlib)# 會(huì)生成一張名為“studentScore.jpg”的圖片def GenerateScorePic(scoreList):

# 解析成績(jī)列表,生成橫縱坐標(biāo)列表

xNameList = [str(studentInfo[0]) for studentInfo in scoreList]

yScoreList = [int(studentInfo[1]) for studentInfo in scoreList]

print(“xNameList”,xNameList)

print(“yScoreList”,yScoreList)

# 設(shè)置字體格式

matplotlib.rcParams[‘font.sans-serif’] = [‘SimHei’] # 用黑體顯示中文

# 設(shè)置繪圖尺寸

plt.figure(figsize=(10,5))

# 繪制圖像

plt.bar(x=xNameList, height=yScoreList, label=‘學(xué)生成績(jī)’, color=‘steelblue’, alpha=0.8)

# 在柱狀圖上顯示具體數(shù)值, ha參數(shù)控制水平對(duì)齊方式, va控制垂直對(duì)齊方式

for x1, yy in scoreList:

plt.text(x1, yy + 1, str(yy), ha=‘center’, va=‘bottom’, fontsize=16, rotation=0)

# 設(shè)置標(biāo)題

plt.title(“學(xué)生成績(jī)柱狀圖”)

# 為兩條坐標(biāo)軸設(shè)置名稱

plt.xlabel(“學(xué)生姓名”)

plt.ylabel(“學(xué)生成績(jī)”)

# 顯示圖例

plt.legend()

# 坐標(biāo)軸旋轉(zhuǎn)

plt.xticks(rotation=90)

# 設(shè)置底部比例,防止橫坐標(biāo)顯示不全

plt.gcf().subplots_adjust(bottom=0.25)

# 保存為圖片

plt.savefig(“studentScore.jpg”)

# 直接顯示

plt.show()

# 開始生成報(bào)告def GenerateScoreReport(scoreOrder,picPath):

# 新建一個(gè)文檔

document = Document()

# 設(shè)置標(biāo)題

document.add_heading(‘?dāng)?shù)據(jù)分析報(bào)告’, 0)

# 添加第一名的信息

p1 = document.add_paragraph(“分?jǐn)?shù)排在第一的學(xué)生姓名為: ”)

p1.add_run(scoreOrder[0][0]).bold = True

p1.add_run(“ 分?jǐn)?shù)為: ”)

p1.add_run(str(scoreOrder[0][1])).italic = True

# 添加總體情況信息

p2 = document.add_paragraph(“共有: ”)

p2.add_run(str(len(scoreOrder))).bold = True

p2.add_run(“ 名學(xué)生參加了考試,學(xué)生考試的總體情況: ”)

# 添加考試情況表格

table = document.add_table(rows=1, cols=2)

table.style = ‘Medium Grid 1 Accent 1’

hdr_cells = table.rows[0].cells

hdr_cells[0].text = ‘學(xué)生姓名’

hdr_cells[1].text = ‘學(xué)生分?jǐn)?shù)’

for studentName,studentScore in scoreOrder:

row_cells = table.add_row().cells

row_cells[0].text = studentName

row_cells[1].text = str(studentScore)

# 添加學(xué)生成績(jī)柱狀圖

document.add_picture(picPath, width=Inches(6))

document.save(‘學(xué)生成績(jī)報(bào)告.docx’)

if __name__ == “__main__”:

# 調(diào)用信息獲取方法,獲取用戶信息

nameList,scoreList = GetExcelInfo()

# print(“nameList:”,nameList)

# print(“ScoreList:”,scoreList)

# 將名字和分?jǐn)?shù)列表合并成字典(將學(xué)生姓名和分?jǐn)?shù)關(guān)聯(lián)起來)

scoreDictionary = dict(zip(nameList, scoreList))

# print(“dictionary:”,scoreDictionary)

# 對(duì)字典進(jìn)行值排序,高分在前,reverse=True 代表降序排列

scoreOrder = sorted(scoreDictionary.items(), key=lambda x: x[1], reverse=True)

# print(“scoreOrder”,scoreOrder)

# 將進(jìn)行排序后的學(xué)生成績(jī)列表生成柱狀圖

GenerateScorePic(scoreOrder)

# 開始生成報(bào)告

picPath = “studentScore.jpg”

GenerateScoreReport(scoreOrder,picPath)

print(“任務(wù)完成,報(bào)表生成完畢!”)

Python-docx 修改舊 word 文檔回顧:打開舊文檔,并另存為新文檔

我們這里就拿上一節(jié)生成的學(xué)生成績(jī)報(bào)告作為示例:

from docx import Document

if __name__ == “__main__”:

document = Document(‘6 學(xué)生成績(jī)報(bào)告.docx’)

# 在這里進(jìn)行操作,此處忽略

document.save(‘修改后的報(bào)告.docx’)

讀取word文檔的內(nèi)容

示例代碼:

from docx import Document

if __name__ == “__main__”:

document = Document(‘6 學(xué)生成績(jī)報(bào)告.docx’)

# 讀取 word 中所有內(nèi)容

for p in document.paragraphs:

print(“paragraphs:”,p.text)

# 讀取 word 中所有一級(jí)標(biāo)題

for p in document.paragraphs:

if p.style.name == ‘Heading 1’:

print(“Heading 1:”,p.text)

# 讀取 word 中所有二級(jí)標(biāo)題

for p in document.paragraphs:

if p.style.name == ‘Heading 2’:

print(“Heading 2:”, p.text)

# 讀取 word 中所有正文

for p in document.paragraphs:

if p.style.name == ‘Normal’:

print(“Normal:”, p.text)

document.save(‘修改后的報(bào)告.docx’)

讀取docx中表格內(nèi)

示例代碼:

from docx import Document

if __name__ == “__main__”:

document = Document(‘6 學(xué)生成績(jī)報(bào)告.docx’)

# 讀取表格內(nèi)容

for tb in document.tables:

for i,row in enumerate(tb.rows):

for j,cell in enumerate(row.cells):

text = ‘’

for p in cell.paragraphs:

text += p.text

print(f‘第{i}行,第{j}列的內(nèi)容{text}’)

document.save(‘修改后的報(bào)告.docx’)

修改word中的內(nèi)容

示例代碼:

from docx import Document

if __name__ == “__main__”:

document = Document(‘6 學(xué)生成績(jī)報(bào)告.docx’)

# 修改 word 中所有內(nèi)容

for p in document.paragraphs:

p.text = “修改后的段落內(nèi)容”

# 修改表格內(nèi)容

for tb in document.tables:

for i,row in enumerate(tb.rows):

for j,cell in enumerate(row.cells):

text = ‘’

for p in cell.paragraphs:

p.text = (“第”,str(i),“行”,str(j),“列”)

print(f‘第{i}行,第{j}列的內(nèi)容{text}’)

document.save(‘6.4 修改后的報(bào)告.docx’)

docx-mailmerge 自動(dòng)生成萬(wàn)份勞動(dòng)合同創(chuàng)建合同模板

添加內(nèi)容框架

創(chuàng)建一個(gè)域

設(shè)置域名

依次全部添加

生成1份證明

示例代碼:

from mailmerge import MailMerge

template = ‘薪資證明模板.docx’

document = MailMerge(template)

document.merge(name = ‘唐星’,

id = ‘1010101010’,

year = ‘2020’,

salary = ‘99999’,

job = ‘嵌入式軟件開發(fā)工程師’)

document.write(‘生成的1份證明.docx’)

哈哈哈哈!!月入10萬(wàn),走向人生巔峰~

生成10000份證明

示例代碼:

from mailmerge import MailMerge

from datetime import datetime

# 生成單份合同def GenerateCertify(templateName,newName):

# 打開模板

document = MailMerge(templateName)

# 替換內(nèi)容

document.merge(name=‘唐星’,

id=‘1010101010’,

year=‘2020’,

salary=‘99999’,

job=‘嵌入式軟件開發(fā)工程師’)

# 保存文件

document.write(newName)

if __name__ == “__main__”:

templateName = ‘薪資證明模板.docx’

# 獲得開始時(shí)間

startTime = datetime.now()

# 開始生成

for i in range(10000):

newName = f‘。/10000份證明/薪資證明{i}.docx’

GenerateCertify(templateName,newName)

# 獲取結(jié)束時(shí)間

endTime = datetime.now()

# 計(jì)算時(shí)間差

allSeconds = (endTime - startTime).seconds

print(“生成10000份合同一共用時(shí): ”,str(allSeconds),“ 秒”)

print(“程序結(jié)束!”)

只花了89秒,平均不到 0.01 就能生成一個(gè)!!快

74d84460-0d7c-11ec-8fb8-12bb97331649.png

責(zé)任編輯:haq

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點(diǎn)僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場(chǎng)。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請(qǐng)聯(lián)系本站處理。 舉報(bào)投訴
  • 自動(dòng)化
    +關(guān)注

    關(guān)注

    29

    文章

    5622

    瀏覽量

    79663
  • python
    +關(guān)注

    關(guān)注

    56

    文章

    4807

    瀏覽量

    85039

原文標(biāo)題:Python自動(dòng)化辦公之Word,全網(wǎng)最全看這一篇就夠了

文章出處:【微信號(hào):AndroidPush,微信公眾號(hào):Android編程精選】歡迎添加關(guān)注!文章轉(zhuǎn)載請(qǐng)注明出處。

收藏 人收藏

    評(píng)論

    相關(guān)推薦

    華為云 Flexus X 實(shí)例評(píng)測(cè)使用體驗(yàn)——Anaconda 環(huán)境安裝

    Anaconda 是 python 開發(fā)最常用環(huán)境,那么我們今天使用【華為云 Flexus X 實(shí)例】來搭建一下這個(gè)環(huán)境,希望本文能對(duì) python 開發(fā)者們有一定的價(jià)值,當(dāng)然,這里也
    的頭像 發(fā)表于 01-21 16:13 ?112次閱讀
    華為云 Flexus X 實(shí)例評(píng)測(cè)使用體驗(yàn)——Anaconda <b class='flag-5'>環(huán)境</b><b class='flag-5'>安裝</b>

    使用Python實(shí)現(xiàn)xgboost教程

    使用Python實(shí)現(xiàn)XGBoost模型通常涉及以下幾個(gè)步驟:數(shù)據(jù)準(zhǔn)備、模型訓(xùn)練、模型評(píng)估和模型預(yù)測(cè)。以下是一個(gè)詳細(xì)的教程,指導(dǎo)你如何在Python中使用XGBoost。 1. 安裝XG
    的頭像 發(fā)表于 01-19 11:21 ?399次閱讀

    Flexus 云服務(wù)器 X:Python 安裝的極致便捷之旅

    配置和環(huán)境設(shè)置方面,可能會(huì)遇到各種挑戰(zhàn)。為了幫助開發(fā)者更高效地使用 Flexus 云服務(wù)器 X,本文將詳細(xì)介紹如何在 Flexus 云服務(wù)器 X 上安裝 Python,并突出其便捷性。
    的頭像 發(fā)表于 01-07 17:00 ?120次閱讀
    Flexus 云服務(wù)器 X:<b class='flag-5'>Python</b> <b class='flag-5'>安裝</b>的極致便捷之旅

    電腦是已經(jīng)安裝python2.7,為什么打開GUI的script window時(shí),一直提示未找到python2.7?

    電腦是已經(jīng)安裝python2.7,為什么打開GUI的script window時(shí),一直提示未找到python2.7?
    發(fā)表于 11-14 07:50

    Docker運(yùn)行環(huán)境安裝

    、發(fā)布、測(cè)試和部署,可以幫助開發(fā)人員將最新版本代碼應(yīng)用到生產(chǎn)環(huán)境中。 Docker可以安裝在多個(gè)平臺(tái)中,包括Mac、Windows和Linux。不過,生產(chǎn)環(huán)境還是推薦在Linux上運(yùn)行,以下以主流的Linux
    的頭像 發(fā)表于 10-29 11:28 ?278次閱讀

    pycharm配置pytorch運(yùn)行環(huán)境

    在PyCharm中配置PyTorch運(yùn)行環(huán)境主要包括安裝PyCharm、安裝Python(如果尚未安裝)、配置PyTorch
    的頭像 發(fā)表于 08-01 16:25 ?1754次閱讀

    pycharm怎么配置pytorch環(huán)境

    1. 安裝PyCharm 首先,確保您已經(jīng)安裝了PyCharm。PyCharm是JetBrains公司開發(fā)的一款流行的Python集成開發(fā)環(huán)境(IDE)。您可以從JetBrains官網(wǎng)
    的頭像 發(fā)表于 08-01 15:40 ?1171次閱讀

    python寫驗(yàn)證環(huán)境cocotb

    本文介紹了cocotb的安裝python tb文件的寫法、用xrun仿真cocotb的腳本等,我們來看看體驗(yàn)如何。
    的頭像 發(fā)表于 07-24 09:38 ?619次閱讀
    用<b class='flag-5'>python</b>寫驗(yàn)證<b class='flag-5'>環(huán)境</b>cocotb

    如何實(shí)現(xiàn)Python復(fù)制文件操作

    Python 中有許多“開蓋即食”的模塊(比如 os,subprocess 和 shutil)以支持文件 I/O 操作。在這篇文章中,你將會(huì)看到一些用 Python 實(shí)現(xiàn)文件復(fù)制的特殊方法。下面我們開始學(xué)習(xí)這九種不同的方法來實(shí)現(xiàn)
    的頭像 發(fā)表于 07-18 14:53 ?478次閱讀

    pycharm如何訓(xùn)練機(jī)器學(xué)習(xí)模型

    PyCharm是一個(gè)流行的Python集成開發(fā)環(huán)境(IDE),它提供了豐富的功能,包括代碼編輯、調(diào)試、測(cè)試等。在本文中,我們將介紹如何在PyCharm中訓(xùn)練機(jī)器學(xué)習(xí)模型。 一、安裝Py
    的頭像 發(fā)表于 07-11 10:14 ?942次閱讀

    用pycharm進(jìn)行python爬蟲的步驟

    以下是使用PyCharm進(jìn)行Python爬蟲的步驟: 安裝PyCharm和Python 首先,您需要安裝PyCharm和Python。PyC
    的頭像 發(fā)表于 07-11 10:11 ?952次閱讀

    編譯ESP-AT工程,運(yùn)行python build.py install命令提示符遇到的疑問求解

    你好,我按照“編譯 ESP-AT 工程”步驟操作時(shí)候,走到第三步:安裝環(huán)境,運(yùn)行python build.py install命令提示符,顯示 C
    發(fā)表于 06-27 06:05

    安裝依賴的Python軟件包時(shí)報(bào)錯(cuò)如何解決?

    安裝依賴的 Python 軟件包,出現(xiàn)了如下錯(cuò)誤,請(qǐng)問如何解決,謝謝! Command \"E:/msys32/mingw32/bin/python2.7.exe E:/msys32
    發(fā)表于 06-26 07:32

    何在離線環(huán)境安裝VSCode的ESP-IDF擴(kuò)展插件?

    仍然需要連接網(wǎng)絡(luò)配置python環(huán)境下載資源包。于是我將另外一臺(tái)有網(wǎng)絡(luò)并且已安裝完畢的電腦上的一些資源包拷貝過來,可以識(shí)別到資源需求滿足但仍然顯示部分配置缺失,類似如下:Code: Select all
    發(fā)表于 06-13 07:56

    用離線安裝安裝的idf,其創(chuàng)建的Python虛擬環(huán)境無(wú)激活腳本是怎么回事?

    如題,用離線安裝安裝的idf,其創(chuàng)建的Python虛擬環(huán)境無(wú)激活腳本,具體如下圖所示: 反而用vscode插件安裝的idf有,如下圖:vs
    發(fā)表于 06-11 06:49
    金沙城百家乐官网大赛规则| 瑞士百家乐的玩法技巧和规则| 优博百家乐官网的玩法技巧和规则| 百家乐官网视频下载地址| 威尼斯人娱乐场 五星| 百家乐2号机器投注技巧| 御匾会百家乐官网的玩法技巧和规则| 大发888被查封| 澳门百家乐群代理| 百家乐翻天主题曲| 百家乐心得分享| 免费玩百家乐官网的玩法技巧和规则 | 百家乐官网视频美女| 百家乐官网桌子北京| 大发888娱乐场888| ea百家乐打水| 王子百家乐官网的玩法技巧和规则 | 百家乐官网vshow| 太阳城娱乐网| 大发888手机版| 百家乐有送体验金| 中骏百家乐官网的玩法技巧和规则 | 永利百家乐娱乐| 百家乐官网娱乐城官方网| 足球投注开户| 百家乐桌子租| 百家乐时时彩网站| 米其林百家乐官网的玩法技巧和规则 | 百家乐官网玩法教程| 在线娱乐城注册送彩金| 百家乐强对弱的对打法| 风水24山分房图| 澳门百家乐官网技巧经| 新锦江百家乐官网娱乐场| 星际百家乐官网娱乐城| 聚宝盆百家乐的玩法技巧和规则| 百家乐资金注码| 做生意看风水| 百家乐官网群shozo权威| A8百家乐官网的玩法技巧和规则| 回力百家乐官网的玩法技巧和规则|