一区二区三区三上|欧美在线视频五区|国产午夜无码在线观看视频|亚洲国产裸体网站|无码成年人影视|亚洲AV亚洲AV|成人开心激情五月|欧美性爱内射视频|超碰人人干人人上|一区二区无码三区亚洲人区久久精品

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

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

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

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

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

作者丨超級大洋蔥806

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

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

升級pip(便于安裝最新庫)

python -m pip install -U pip setuptools

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

安裝方法:

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 的繪圖庫,本期簡單講解,后期會有專門的課程)

安裝方法:

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文檔自動化”)

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

document = Document()

document.save(‘new.docx’)

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

# 我是華麗的分隔符

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

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

GenerateNewWord(newname)

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

舊文檔:

示例代碼:

from docx import Document

document = Document(‘exist.docx’)

document.save(‘new.docx’)

也許你會說,沒有沒搞錯,就這三句話?是的,就這三句,你就完成了舊文檔的復(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文件絕對路徑名

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ú)立的進(jìn)程:

# word = DispatchEx(‘Word.Application’)

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

word.Visible = 1 # 0:后臺運(yùn)行 1:前臺運(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ú)立的進(jìn)程:

# word = DispatchEx(’Word.Application‘)

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

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

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

doc = word.Documents.Open(os.getcwd() + “\3.1 win32com測試.docx”) # 打開一個已有的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 # 后臺運(yùn)行,不顯示

word.DisplayAlerts = 0 # 不警告

doc = word.Documents.Open(os.getcwd() + “\3.3 win32com轉(zhuǎn)換word為pdf等格式.docx”) # 打開一個已有的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)入庫操作

from docx import Document

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

from docx.shared import Inches

新建一個文檔

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)題和項目列表(如項目符號)。

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)題操作

等級1-9 也就是標(biāo)題1-標(biāo)題9,我們可以在舊文檔中將標(biāo)題格式設(shè)置好,使用Python-docx打開舊文檔,再添加相應(yīng)等級標(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’

添加無序列表操作

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

添加圖片操作

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

第二個參數(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

添加分頁符操作

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 自動生成數(shù)據(jù)分析報告最終效果

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

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

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)

# 獲取單個表格值 (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í)成績信息def GetExcelInfo():

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

# 打開指定文檔

xlsx = xlrd.open_workbook(‘學(xué)生成績表格.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

柱狀圖生成

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

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

scoreDictionary = dict(zip(nameList, scoreList))

print(“dictionary:”,scoreDictionary)

# 對字典進(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é)生成績柱狀圖(使用matplotlib)# 會生成一張名為“studentScore.jpg”的圖片def GenerateScorePic(scoreList):

# 解析成績列表,生成橫縱坐標(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é)生成績’, color=‘steelblue’, alpha=0.8)

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

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é)生成績柱狀圖”)

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

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

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

# 顯示圖例

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()

生成最終報告

代碼如下:

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

# 新建一個文檔

document = Document()

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

document.add_heading(‘?dāng)?shù)據(jù)分析報告’, 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é)生成績柱狀圖

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

document.save(‘學(xué)生成績報告.docx’)

完整代碼

import xlrd

import matplotlib

import matplotlib.pyplot as plt

from docx import Document

from docx.shared import Inches

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

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

# 打開指定文檔

xlsx = xlrd.open_workbook(‘學(xué)生成績表格.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é)生成績柱狀圖(使用matplotlib)# 會生成一張名為“studentScore.jpg”的圖片def GenerateScorePic(scoreList):

# 解析成績列表,生成橫縱坐標(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é)生成績’, color=‘steelblue’, alpha=0.8)

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

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é)生成績柱狀圖”)

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

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

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

# 顯示圖例

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()

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

# 新建一個文檔

document = Document()

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

document.add_heading(‘?dāng)?shù)據(jù)分析報告’, 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é)生成績柱狀圖

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

document.save(‘學(xué)生成績報告.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)

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

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

# print(“scoreOrder”,scoreOrder)

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

GenerateScorePic(scoreOrder)

# 開始生成報告

picPath = “studentScore.jpg”

GenerateScoreReport(scoreOrder,picPath)

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

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

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

from docx import Document

if __name__ == “__main__”:

document = Document(‘6 學(xué)生成績報告.docx’)

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

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

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

示例代碼:

from docx import Document

if __name__ == “__main__”:

document = Document(‘6 學(xué)生成績報告.docx’)

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

for p in document.paragraphs:

print(“paragraphs:”,p.text)

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

for p in document.paragraphs:

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

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

# 讀取 word 中所有二級標(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(‘修改后的報告.docx’)

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

示例代碼:

from docx import Document

if __name__ == “__main__”:

document = Document(‘6 學(xué)生成績報告.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(‘修改后的報告.docx’)

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

示例代碼:

from docx import Document

if __name__ == “__main__”:

document = Document(‘6 學(xué)生成績報告.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 修改后的報告.docx’)

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

添加內(nèi)容框架

創(chuàng)建一個域

設(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’)

哈哈哈哈?。≡氯?0萬,走向人生巔峰~

生成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’

# 獲得開始時間

startTime = datetime.now()

# 開始生成

for i in range(10000):

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

GenerateCertify(templateName,newName)

# 獲取結(jié)束時間

endTime = datetime.now()

# 計算時間差

allSeconds = (endTime - startTime).seconds

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

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

只花了89秒,平均不到 0.01 就能生成一個?。】?/p>

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

責(zé)任編輯:haq

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

    關(guān)注

    29

    文章

    5725

    瀏覽量

    81254
  • python
    +關(guān)注

    關(guān)注

    56

    文章

    4822

    瀏覽量

    85874

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

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

收藏 人收藏

    評論

    相關(guān)推薦

    何在計算機(jī)上安裝麒麟操作系統(tǒng)Kylin V10 SP3

    麒麟操作系統(tǒng) Kylin V10 SP3 是一款基于 Linux 的操作系統(tǒng),廣泛應(yīng)用于政府、企業(yè)和個人用戶。本文將詳細(xì)介紹如何在計算機(jī)上安裝麒麟
    的頭像 發(fā)表于 04-11 15:32 ?653次閱讀
    如<b class='flag-5'>何在</b>計算機(jī)上<b class='flag-5'>安裝</b>麒麟<b class='flag-5'>操作</b>系統(tǒng)Kylin V10 SP3

    告別復(fù)雜的終極指南:如何在樹莓派上安裝 Manjaro:2024

    如果你想在RaspberryPi上體驗ArchLinux,Manjaro可能是你的最佳選擇。它基于Arch,但被打包成一個傳統(tǒng)的Linux發(fā)行版,支持多種桌面環(huán)境和架構(gòu)。讓我們來學(xué)習(xí)如何在RaspberryPi上安裝它。什么是L
    的頭像 發(fā)表于 03-25 09:39 ?301次閱讀
    告別復(fù)雜的終極指南:如<b class='flag-5'>何在</b>樹莓派上<b class='flag-5'>安裝</b> Manjaro:2024

    ?如何在虛擬環(huán)境中使用 Python,提升你的開發(fā)體驗~

    RaspberryPiOS預(yù)裝了Python,你需要使用其虛擬環(huán)境安裝包。今天出版的最新一期《TheMagPi》雜志刊登了我們文檔負(fù)責(zé)人NateContino撰寫的一篇實(shí)用教程,幫助你入門
    的頭像 發(fā)表于 03-25 09:34 ?139次閱讀
    ?如<b class='flag-5'>何在</b>虛擬<b class='flag-5'>環(huán)境</b>中使用 <b class='flag-5'>Python</b>,提升你的開發(fā)體驗~

    零基礎(chǔ)入門:如何在樹莓派上編寫和運(yùn)行Python程序?

    在這篇文章中,我將為你簡要介紹Python程序是什么、Python程序可以用來做什么,以及如何在RaspberryPi上編寫和運(yùn)行一個簡單的Python程序。什么是
    的頭像 發(fā)表于 03-25 09:27 ?312次閱讀
    零基礎(chǔ)入門:如<b class='flag-5'>何在</b>樹莓派上編寫和運(yùn)行<b class='flag-5'>Python</b>程序?

    人臉識別指南:如何在樹莓派上安裝和設(shè)置 Dlib

    學(xué)習(xí)如何在樹莓派上安裝Dlib并配置人臉識別功能,為您的AI項目奠定基礎(chǔ)。在樹莓派上安裝Dlib的詳細(xì)步驟要為樹莓派安裝Dlib并確保人臉識別項目順利運(yùn)行,請按照以下詳細(xì)步驟
    的頭像 發(fā)表于 03-24 17:31 ?426次閱讀
    人臉識別指南:如<b class='flag-5'>何在</b>樹莓派上<b class='flag-5'>安裝</b>和設(shè)置 Dlib

    Spire.Cloud.Word云端Word文檔處理SDK介紹

    Spire.Cloud.Word 是一款專業(yè)的云端 Word 文檔處理 SDK,開發(fā)人員使用它在云端創(chuàng)建、讀取、編輯、轉(zhuǎn)換和保存 Word 文檔。作為一款完全獨(dú)立的組件,運(yùn)行環(huán)境無需
    的頭像 發(fā)表于 02-11 11:11 ?349次閱讀
    Spire.Cloud.<b class='flag-5'>Word</b>云端<b class='flag-5'>Word</b>文檔處理SDK介紹

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

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

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

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

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

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

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

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

    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 ?1395次閱讀

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

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

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

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

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

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

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

    如題,用離線安裝安裝的idf,其創(chuàng)建的Python虛擬環(huán)境無激活腳本,具體如下圖所示: 反而用vscode插件安裝的idf有,如下圖:vs
    發(fā)表于 06-11 06:49