哈哈哈哈哈操欧洲电影,久草网在线,亚洲久久熟女熟妇视频,麻豆精品色,久久福利在线视频,日韩中文字幕的,淫乱毛视频一区,亚洲成人一二三,中文人妻日韩精品电影

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

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

# word = DispatchEx(‘Word.Application’)

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

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

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

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

# word = DispatchEx(’Word.Application‘)

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

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

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 # 后臺運行,不顯示

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

哈哈哈哈??!月入10萬,走向人生巔峰~

生成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 就能生成一個??!快

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

責(zé)任編輯:haq

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

    關(guān)注

    31

    文章

    5980

    瀏覽量

    90605
  • python
    +關(guān)注

    關(guān)注

    58

    文章

    4882

    瀏覽量

    90281

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

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

收藏 人收藏
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

    評論

    相關(guān)推薦
    熱點推薦

    [VirtualLab] 使用Python運行VirtualLab Fusion光學(xué)仿真

    : https://code.visualstudio.com/docs/python/python-tutorial 請注意,這里我們將演示如何在全局環(huán)境
    發(fā)表于 03-31 09:39

    何在 VisionFive 上使用 Python 包?

    安裝 愿景五.gpio 軟件包: sudo pip install 愿景五.gpio或者,您可以執(zhí)行以下命令: sudo pip3 install 愿景五.gpio (可選)如果將源代碼復(fù)制到
    發(fā)表于 03-30 08:28

    何在 Vision Five 2 上安裝 python 庫?

    這可能是一個完全愚蠢的問題,但我如何在 Vision Five 2 上安裝 python 庫。 使用該命令后,它給了我這個錯誤。 默認(rèn)為用戶安裝,因為普通站點包不可寫 錯誤:找不到滿足
    發(fā)表于 03-06 07:51

    安裝 Python VisionFive_GPIO失敗是哪里出了問題?

    盡管按照最新的文檔,我在安裝 VisionFive.gpio 包時仍然收到錯誤 sudo apt 安裝 libxml2-dev libxslt-dev python3 -m pip 安裝
    發(fā)表于 02-11 06:13

    沒有專利的opencv-python 版本

    費用于商業(yè)產(chǎn)品,僅需保留版權(quán)聲明); 包含所有核心功能:圖片讀取/處理、視頻讀寫、繪圖、形態(tài)學(xué)操作、邊緣檢測(Canny)、閾值分割、輪廓檢測等,滿足 90%+ 開發(fā)場景; 適配 Python 3.13,安裝
    發(fā)表于 12-13 12:37

    Termux中調(diào)試圣誕樹Python代碼

    在Termux中調(diào)試Python代碼(以圣誕樹立例)非常簡單,核心分為環(huán)境準(zhǔn)備、代碼編寫、運行調(diào)試三個步驟,下面一步步教你操作: 一、環(huán)境準(zhǔn)備(首次使用需做) Termux默認(rèn)可能沒有
    發(fā)表于 12-09 09:02

    pdf轉(zhuǎn)換成word文檔格式亂了

    df轉(zhuǎn)換成word文檔格式亂了 ? 將 pdf 轉(zhuǎn)為 word 是常見的操作,但很多人發(fā)現(xiàn)結(jié)果很亂,文字會移位,字體變化,表格斷裂,圖片偏離原位.這是因為 pdf 存儲的是最終的排版用于顯示或打印
    的頭像 發(fā)表于 11-22 10:04 ?1291次閱讀

    目前最新版的userapps如何安裝D1s環(huán)境?

    https://club.rt-thread.org/ask/article/bd9c5cb55e0bc8f5.html目前按照這個指南安裝D1s的環(huán)境 最新代碼直接找不到 tools
    發(fā)表于 09-25 07:33

    MA35-RTT如何安裝 Python 和 Libusb (Windows) ?

    MA35-RTT:如何安裝 Python 和 Libusb (Windows) ?
    發(fā)表于 09-03 08:30

    termux如何搭建python游戲

    模擬器,支持通過APT包管理器安裝軟件。搭建Python游戲開發(fā)環(huán)境前需完成以下基礎(chǔ)配置: 1. 更換國內(nèi)源 為提升下載速度,需替換Termux默認(rèn)源為清華源,執(zhí)行以下命令: ```bash
    發(fā)表于 08-29 07:06

    何在樹莓派上安裝Ubuntu MATE ?

    如果你對樹莓派操作系統(tǒng)感到厭倦,又對龐大的Ubuntu環(huán)境不太感興趣,那么UbuntuMATE或許值得一試,它適合桌面使用。UbuntuMATE基于Ubuntu,但使用的是更輕量級的MATE桌面環(huán)境
    的頭像 發(fā)表于 08-12 18:56 ?3423次閱讀
    如<b class='flag-5'>何在</b>樹莓派上<b class='flag-5'>安裝</b>Ubuntu MATE ?

    初學(xué)者指南:樹莓派上搭建虛擬環(huán)境!

    在這篇簡明扼要的指南中,我們將探討如何在樹莓派上設(shè)置和使用虛擬環(huán)境(或稱為Venv)——包括在終端和Thonny集成開發(fā)環(huán)境中。使用Bookworm操作系統(tǒng)或更高版本時,或在嘗試
    的頭像 發(fā)表于 07-27 13:24 ?1153次閱讀
    初學(xué)者指南:樹莓派上搭建虛擬<b class='flag-5'>環(huán)境</b>!

    linux虛擬環(huán)境中調(diào)用Linux 版matlab編譯的python庫時出錯

    、readme.txt、 requiredMCRProducts.txt、init.py、CAO_python.ctf。 在linux環(huán)境中按照以下步驟安裝matlab runtime2018b: ① cd到MCR
    發(fā)表于 07-18 10:40

    何在樹莓派上安裝并運行 Arduino 集成開發(fā)環(huán)境

    ,我們將介紹如何在樹莓派上安裝并運行ArduinoIDE。所需物品要在樹莓派上運行ArduinoIDE,你需要以下組件:配備適當(dāng)電源的樹莓派4開發(fā)板HDMI顯示器或電
    的頭像 發(fā)表于 07-01 17:41 ?4532次閱讀
    如<b class='flag-5'>何在</b>樹莓派上<b class='flag-5'>安裝</b>并運行 Arduino 集成開發(fā)<b class='flag-5'>環(huán)境</b>!

    Linux環(huán)境再升級:PLIN驅(qū)動程序正式發(fā)布

    PLIN驅(qū)動程序現(xiàn)已正式發(fā)布,本文將展示如何安裝PLIN驅(qū)動程序,以及如何在Linux環(huán)境下進(jìn)行基本的PLIN通信操作,確保您能夠快速掌握并應(yīng)用這一新工具。
    的頭像 發(fā)表于 04-21 15:29 ?1198次閱讀
    Linux<b class='flag-5'>環(huán)境</b>再升級:PLIN驅(qū)動程序正式發(fā)布
    东城区| 靖安县| 许昌市| 安仁县| 平顶山市| 汤阴县| 诏安县| 兰坪| 苍溪县| 固始县| 运城市| 增城市| 文安县| 永福县| 双城市| 惠水县| 西乌珠穆沁旗| 大港区| 临湘市| 玛曲县| 池州市| 扶风县| 铁岭县| 吴川市| 岳普湖县| 景德镇市| 衡水市| 砀山县| 萨迦县| 顺义区| 仪征市| 临颍县| 昭觉县| 温宿县| 黄骅市| 鸡西市| 上杭县| 长葛市| 古丈县| 万州区| 会泽县|