18video性欧美19sex,欧美高清videosddfsexhd,性少妇videosexfreexxx片中国,激情五月激情综合五月看花,亚洲人成网77777色在线播放

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

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內不再提示

如何在環(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大部分情況都是寫操作,也有少許情況會用到讀操作,在本次教程中都會進行講解,本次課程主要用到以下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轉docx格式轉換用)

安裝方法:

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(“大家好!我們今天開始學習word文檔自動化”)

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

document = Document()

document.save(‘new.docx’)

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

# 我是華麗的分隔符

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

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

GenerateNewWord(newname)

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

舊文檔:

示例代碼:

from docx import Document

document = Document(‘exist.docx’)

document.save(‘new.docx’)

也許你會說,沒有沒搞錯,就這三句話?是的,就這三句,你就完成了舊文檔的復制,如果你想修改,直接添加內容就行了呢!

win32com 將 doc 轉為 docx舊文檔:

示例代碼:

import os

from win32com import client as wc

def TransDocToDocx(oldDocName,newDocxName):

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

# 打開word應用程序

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

# 打開 舊word 文件

doc = word.Documents.Open(oldDocName)

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

doc.SaveAs(newDocxName, 12)

# 關閉word文檔

doc.Close()

word.Quit()

print(“生成完畢!”)

if __name__ == “__main__”:

# 獲取當前目錄完整路徑

currentPath = os.getcwd()

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

# 獲取 舊doc格式word文件絕對路徑名

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

print(“docFilePath = ”, docName)

# 設置新docx格式文檔文件名

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

TransDocToDocx(docName,docxName)

win32com 操作 word打開新的word文檔并添加內容

示例代碼:

import win32com

from win32com.client import Dispatch, constants

import os

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

word = Dispatch(‘Word.Application’)

# 或者使用下面的方法,使用啟動獨立的進程:

# word = DispatchEx(‘Word.Application’)

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

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

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

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

doc = word.Documents.Add()

# 在文檔開頭添加內容

myRange1 = doc.Range(0, 0)

myRange1.InsertBefore(‘Hello word

’)

# 在文檔末尾添加內容

myRange2 = doc.Range()

myRange2.InsertAfter(‘Bye word

’)

# 在文檔i指定位置添加內容

i = 0

myRange3 = doc.Range(0, i)

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

”)

# doc.Save() # 保存

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

doc.Close() # 關閉 word 文檔

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

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

print(“調用funOpenNewFile()”)

funOpenNewFile()

打開已存在word文檔并添加內容

前提條件:

示例代碼:

import win32com

from win32com.client import Dispatch, constants

import os

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

word = Dispatch(’Word.Application‘)

# 或者使用下面的方法,使用啟動獨立的進程:

# word = DispatchEx(’Word.Application‘)

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

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

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

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

# 在文檔開頭添加內容

myRange1 = doc.Range(0, 0)

myRange1.InsertBefore(’Hello word

‘)

# 在文檔末尾添加內容

myRange2 = doc.Range()

myRange2.InsertAfter(’Bye word

‘)

# 在文檔i指定位置添加內容

i = 0

myRange3 = doc.Range(0, i)

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

”)

# doc.Save() # 保存

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

doc.Close() # 關閉 word 文檔

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

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

print(“調用funOpenExistFile()”)

funOpenExistFile()

轉換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轉換word為pdf等格式.docx”) # 打開一個已有的word文檔

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

doc.Close()

word.Quit()

if __name__ == ‘__main__’:

funGeneratePDF()

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

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官方例程解析

導入庫操作

from docx import Document

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

from docx.shared import Inches

新建一個文檔

document = Document()

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

document = Document(‘exist.docx’)

添加標題段落

document.add_heading(‘Document Title’, 0)

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

添加段落操作

段落在 Word 中是基本內容。它們用于正文文本,也用于標題和項目列表(如項目符號)。

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 # 添加斜體文字

添加標題操作

等級1-9 也就是標題1-標題9,我們可以在舊文檔中將標題格式設置好,使用Python-docx打開舊文檔,再添加相應等級標題即可。

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)

填充標題行操作

hdr_cells = table.rows[0].cells

hdr_cells[0].text = ‘Qty’

hdr_cells[1].text = ‘Id’

hdr_cells[2].text = ‘Desc’

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

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

設置標題樣式操作

table.style = ‘LightShading-Accent1’

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

添加分頁符操作

document.add_page_break()

保存當前文檔操作

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

Python-docx 表格樣式設置

表格樣式設置代碼:

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 = ‘第一列內容’

heading_cells[1].text = ‘第二列內容’

heading_cells[2].text = ‘第三列內容’

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 = ‘第一列內容’

heading_cells[1].text = ‘第二列內容’

heading_cells[2].text = ‘第三列內容’

document.add_paragraph(“

”)

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

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

docx&matplotlib 自動生成數(shù)據分析報告最終效果

數(shù)據獲取

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

import xlrd

xlsx = xlrd.open_workbook(‘。/3_1 xlrd 讀取 操作練習.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)

表格內容:

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

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

# 獲取學習成績信息def GetExcelInfo():

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

# 打開指定文檔

xlsx = xlrd.open_workbook(‘學生成績表格.xlsx’)

# 獲取sheet

sheet = xlsx.sheet_by_index(0)

# 獲取表格行數(shù)

nrows = sheet.nrows

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

# 獲取第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)]

# 返回名字列表和分數(shù)列表

return nameList,scoreList

獲取結果:

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

柱狀圖生成

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

# 將名字和分數(shù)列表合并成字典(將學生姓名和分數(shù)關聯(lián)起來)

scoreDictionary = dict(zip(nameList, scoreList))

print(“dictionary:”,scoreDictionary)

# 對字典進行值排序,高分在前,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}

# 排序后,再次轉換成列表

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 生成柱狀圖:

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

# 解析成績列表,生成橫縱坐標列表

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

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

print(“xNameList”,xNameList)

print(“yScoreList”,yScoreList)

# 設置字體格式

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

# 設置繪圖尺寸

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

# 繪制圖像

plt.bar(x=xNameList, height=yScoreList, label=‘學生成績’, 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)

# 設置標題

plt.title(“學生成績柱狀圖”)

# 為兩條坐標軸設置名稱

plt.xlabel(“學生姓名”)

plt.ylabel(“學生成績”)

# 顯示圖例

plt.legend()

# 坐標軸旋轉

plt.xticks(rotation=90)

# 設置底部比例,防止橫坐標顯示不全

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

# 保存為圖片

plt.savefig(“studentScore.jpg”)

# 直接顯示

plt.show()

生成最終報告

代碼如下:

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

# 新建一個文檔

document = Document()

# 設置標題

document.add_heading(‘數(shù)據分析報告’, 0)

# 添加第一名的信息

p1 = document.add_paragraph(“分數(shù)排在第一的學生姓名為: ”)

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

p1.add_run(“ 分數(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(“ 名學生參加了考試,學生考試的總體情況: ”)

# 添加考試情況表格

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 = ‘學生姓名’

hdr_cells[1].text = ‘學生分數(shù)’

for studentName,studentScore in scoreOrder:

row_cells = table.add_row().cells

row_cells[0].text = studentName

row_cells[1].text = str(studentScore)

# 添加學生成績柱狀圖

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

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

完整代碼

import xlrd

import matplotlib

import matplotlib.pyplot as plt

from docx import Document

from docx.shared import Inches

# 獲取學習成績信息def GetExcelInfo():

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

# 打開指定文檔

xlsx = xlrd.open_workbook(‘學生成績表格.xlsx’)

# 獲取sheet

sheet = xlsx.sheet_by_index(0)

# 獲取表格行數(shù)

nrows = sheet.nrows

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

# 獲取第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)]

# 返回名字列表和分數(shù)列表

return nameList,scoreList

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

# 解析成績列表,生成橫縱坐標列表

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

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

print(“xNameList”,xNameList)

print(“yScoreList”,yScoreList)

# 設置字體格式

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

# 設置繪圖尺寸

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

# 繪制圖像

plt.bar(x=xNameList, height=yScoreList, label=‘學生成績’, 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)

# 設置標題

plt.title(“學生成績柱狀圖”)

# 為兩條坐標軸設置名稱

plt.xlabel(“學生姓名”)

plt.ylabel(“學生成績”)

# 顯示圖例

plt.legend()

# 坐標軸旋轉

plt.xticks(rotation=90)

# 設置底部比例,防止橫坐標顯示不全

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

# 保存為圖片

plt.savefig(“studentScore.jpg”)

# 直接顯示

plt.show()

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

# 新建一個文檔

document = Document()

# 設置標題

document.add_heading(‘數(shù)據分析報告’, 0)

# 添加第一名的信息

p1 = document.add_paragraph(“分數(shù)排在第一的學生姓名為: ”)

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

p1.add_run(“ 分數(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(“ 名學生參加了考試,學生考試的總體情況: ”)

# 添加考試情況表格

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 = ‘學生姓名’

hdr_cells[1].text = ‘學生分數(shù)’

for studentName,studentScore in scoreOrder:

row_cells = table.add_row().cells

row_cells[0].text = studentName

row_cells[1].text = str(studentScore)

# 添加學生成績柱狀圖

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

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

if __name__ == “__main__”:

# 調用信息獲取方法,獲取用戶信息

nameList,scoreList = GetExcelInfo()

# print(“nameList:”,nameList)

# print(“ScoreList:”,scoreList)

# 將名字和分數(shù)列表合并成字典(將學生姓名和分數(shù)關聯(lián)起來)

scoreDictionary = dict(zip(nameList, scoreList))

# print(“dictionary:”,scoreDictionary)

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

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

# print(“scoreOrder”,scoreOrder)

# 將進行排序后的學生成績列表生成柱狀圖

GenerateScorePic(scoreOrder)

# 開始生成報告

picPath = “studentScore.jpg”

GenerateScoreReport(scoreOrder,picPath)

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

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

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

from docx import Document

if __name__ == “__main__”:

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

# 在這里進行操作,此處忽略

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

讀取word文檔的內容

示例代碼:

from docx import Document

if __name__ == “__main__”:

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

# 讀取 word 中所有內容

for p in document.paragraphs:

print(“paragraphs:”,p.text)

# 讀取 word 中所有一級標題

for p in document.paragraphs:

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

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

# 讀取 word 中所有二級標題

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中表格內

示例代碼:

from docx import Document

if __name__ == “__main__”:

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

# 讀取表格內容

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}列的內容{text}’)

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

修改word中的內容

示例代碼:

from docx import Document

if __name__ == “__main__”:

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

# 修改 word 中所有內容

for p in document.paragraphs:

p.text = “修改后的段落內容”

# 修改表格內容

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}列的內容{text}’)

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

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

添加內容框架

創(chuàng)建一個域

設置域名

依次全部添加

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

# 替換內容

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)

# 獲取結束時間

endTime = datetime.now()

# 計算時間差

allSeconds = (endTime - startTime).seconds

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

print(“程序結束!”)

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

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

責任編輯:haq

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

    關注

    29

    文章

    5849

    瀏覽量

    88392
  • python
    +關注

    關注

    56

    文章

    4849

    瀏覽量

    89223

原文標題:Python自動化辦公之Word,全網最全看這一篇就夠了

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

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

掃碼添加小助手

加入工程師交流群

    評論

    相關推薦
    熱點推薦

    termux如何搭建python游戲

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

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

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

    linux虛擬環(huán)境中調用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,你需要以下組件:配備適當電源的樹莓派4開發(fā)板HDMI顯示器或電
    的頭像 發(fā)表于 07-01 17:41 ?1701次閱讀
    如<b class='flag-5'>何在</b>樹莓派上<b class='flag-5'>安裝</b>并運行 Arduino 集成開發(fā)<b class='flag-5'>環(huán)境</b>!

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

    PLIN驅動程序現(xiàn)已正式發(fā)布,本文將展示如何安裝PLIN驅動程序,以及如何在Linux環(huán)境下進行基本的PLIN通信操作,確保您能夠快速掌握并應用這一新工具。
    的頭像 發(fā)表于 04-21 15:29 ?643次閱讀
    Linux<b class='flag-5'>環(huán)境</b>再升級:PLIN驅動程序正式發(fā)布

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

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

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

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

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

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

    零基礎入門:如何在樹莓派上編寫和運行Python程序?

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

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

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

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

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

    操作指南:pytorch云服務器怎么設置?

    設置PyTorch云服務器需選擇云平臺,創(chuàng)建合適的GPU實例,安裝操作系統(tǒng)、Python及Anaconda,創(chuàng)建虛擬環(huán)境,根據CUDA版本安裝
    的頭像 發(fā)表于 02-08 10:33 ?533次閱讀

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

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

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

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

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

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