Python辦公自動(dòng)化解決world文件批量轉(zhuǎn)換
只要是簡單重復(fù)的工作,就想辦法用 Python 來幫你解決吧,人生苦短,你需要 Python。
Word 是辦公軟件中使用頻率非常高的軟件之一了,假如你需要調(diào)整 100 個(gè) Word 文檔的格式保持統(tǒng)一,或者要把 100 個(gè) Word 全部轉(zhuǎn)換為 pdf,那么你就需要 Python 來幫忙了。
python-docx 庫簡介
python-docx 是一個(gè)可以對 Word 進(jìn)行讀寫操作的第三方庫,可以讀取 Word 內(nèi)容,可以為 Word 文檔添加段落、表格、圖片、標(biāo)題,應(yīng)用段落樣式、粗體和斜體、字符樣式。
執(zhí)行如下安裝命令即可完成安裝:
pip install python-docx
官方文檔: https://python-docx.readthedocs.io/
讀取 Word
這里我先創(chuàng)建了一個(gè)樣例,里面有標(biāo)題、正文、表格:

讀取 Word 內(nèi)容的代碼如下:
from docx import Document
def view_docs(docx_file):
# 打開文檔1
doc = Document(docx_file)
# 讀取每段內(nèi)容
pl = [ paragraph.text for paragraph in doc.paragraphs]
# 輸出讀取到的內(nèi)容
for i in pl:
print(i)
def view_docs_table(docx_file):
# 打開文檔1
doc = Document(docx_file)
# 讀取每段內(nèi)容
tables = [table for table in doc.tables]
for table in tables:
for row in table.rows:
for cell in row.cells:
print(cell.text, end=' ')
print()
print('\n')
if __name__ == '__main__':
view_docs("Python自動(dòng)化辦公實(shí)戰(zhàn)課.docx")
view_docs_table("Python自動(dòng)化辦公實(shí)戰(zhàn)課.docx")
運(yùn)行結(jié)果如下:
寫入 Word
現(xiàn)在,用 Python 創(chuàng)建一個(gè)和剛才一樣的 Word 文檔:
from docx import Document
from docx.shared import Pt, RGBColor
from docx.oxml.ns import qn
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.table import _Cell
from docx.oxml import OxmlElement
def set_cell_border(cell: _Cell, **kwargs):
"""
Set cell`s border
Usage:
set_cell_border(
cell,
top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
bottom={"sz": 12, "color": "#00FF00", "val": "single"},
start={"sz": 24, "val": "dashed", "shadow": "true"},
end={"sz": 12, "val": "dashed"},
)
"""
tc = cell._tc
tcPr = tc.get_or_add_tcPr()
# check for tag existnace, if none found, then create one
tcBorders = tcPr.first_child_found_in("w:tcBorders")
if tcBorders is None:
tcBorders = OxmlElement('w:tcBorders')
tcPr.append(tcBorders)
# list over all available tags
for edge in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
edge_data = kwargs.get(edge)
if edge_data:
tag = 'w:{}'.format(edge)
# check for tag existnace, if none found, then create one
element = tcBorders.find(qn(tag))
if element is None:
element = OxmlElement(tag)
tcBorders.append(element)
# looks like order of attributes is important
for key in ["sz", "val", "color", "space", "shadow"]:
if key in edge_data:
element.set(qn('w:{}'.format(key)), str(edge_data[key]))
document = Document()
document.styles['Normal'].font.name = u'宋體'
document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')
##標(biāo)題
def add_header(text, level, align='center'):
title_ = document.add_heading(level=level)
if align == 'center':
title_.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # 標(biāo)題居中
elif align == 'right':
title_.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT # 標(biāo)題居中
title_run = title_.add_run(text) # 添加標(biāo)題內(nèi)容
# title_run.font.size = Pt(24) # 設(shè)置標(biāo)題字體大小
title_run.font.name = 'Times New Roman' # 設(shè)置標(biāo)題西文字體
title_run.font.color.rgb = RGBColor(0, 0, 0) # 字體顏色
title_run.element.rPr.rFonts.set(qn('w:eastAsia'), '微軟雅黑') # 設(shè)置標(biāo)題中文字體
add_header(text='Python自動(dòng)化辦公實(shí)戰(zhàn)', level=1)
add_header(text='Python基礎(chǔ)', level=2, align='left')
document.add_paragraph('Python 是一門面向?qū)ο蟮母呒壘幊陶Z言,易學(xué)易用,是自動(dòng)化辦公首選的工具。')
add_header('Python玩轉(zhuǎn)圖片', level=2, align='left')
document.add_paragraph('圖片是工作中接觸較多的媒體文件了,你可能需要圖片壓縮,加水印,文字識(shí)別等操作')
records = (
('Python 基礎(chǔ)', '00:30', '2021-08-01', ''),
('Python 玩轉(zhuǎn)圖片', '01:00', '2021-08-01', ''),
('Python 玩轉(zhuǎn) Word', '01:00', '2021-08-01', ''),
)
table = document.add_table(rows=1, cols=4)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = '章節(jié)'
hdr_cells[1].text = '時(shí)長'
hdr_cells[2].text = '日期'
hdr_cells[3].text = '備注'
for cell in hdr_cells:
set_cell_border(cell,
top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
bottom={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
start={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
end={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
)
for chapter, time, date, note in records:
row_cells = table.add_row().cells
row_cells[0].text = chapter
row_cells[1].text = time
row_cells[2].text = date
row_cells[3].text = note
for cell in row_cells:
set_cell_border(cell,
top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
bottom={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
start={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
end={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
)
document.save('Python自動(dòng)化辦公實(shí)戰(zhàn).docx')
其中,為表格添加邊框的代碼由于比較復(fù)雜,單獨(dú)做為一個(gè)函數(shù)來調(diào)用。
生成的 Word 文檔如下所示,其中表格邊框的顏色,標(biāo)題的顏色,字體大小,樣式都是可以設(shè)置的:

其他操作
添加分頁符:
document.add_page_break()
添加圖片:
document.add_picture('monty-truth.png', width=Inches(1.25))
設(shè)置表格的列寬和行高
''' 設(shè)置列寬 可以設(shè)置每個(gè)單元格的寬,同列單元格寬度相同,如果定義了不同的寬度將以最大值準(zhǔn) ''' table.cell(0,0).width=Cm(10) #設(shè)置行高 table.rows[0].height=Cm(2)
表格字體的設(shè)定:
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT #設(shè)置整個(gè)表格字體屬性 table.style.font.size=Pt(18) table.style.font.color.rgb=RGBColor(255, 0, 0) table.style.paragraph_format.alignment=WD_PARAGRAPH_ALIGNMENT.CENTER
合并單元格
cell_1=table.cell(1, 0) cell_2=table.cell(2, 1) cell_1.merge(cell_2)
修改文檔字體:
from docx import Document
from docx.shared import Pt #設(shè)置像素、縮進(jìn)等
from docx.shared import RGBColor #設(shè)置字體顏色
from docx.oxml.ns import qn
doc = Document("xxx.docx")
for paragraph in doc.paragraphs:
for run in paragraph.runs:
run.font.bold = True
run.font.italic = True
run.font.underline = True
run.font.strike = True
run.font.shadow = True
run.font.size = Pt(18)
run.font.color.rgb = RGBColor(255,0,255)
run.font.name = "黑體"
# 設(shè)置像黑體這樣的中文字體,必須添加下面 2 行代碼
r = run._element.rPr.rFonts
r.set(qn("w:eastAsia"),"黑體")
doc.save("xxx.docx")
行間距調(diào)整:
paragraph.paragraph_format.line_spacing = 5.0
段前與段后間距調(diào)整:
#段前 paragraph.paragraph_format.space_before = Pt(12) #段后 paragraph.paragraph_format.space_after = Pt(10)
Word 轉(zhuǎn) pdf
只需要兩行代碼就可以將 Word 轉(zhuǎn) pdf,這里使用的是三方庫 docx2pdf 使用前先 pip install docx2pdf。
具體代碼如下所示:
from docx2pdf import convert
convert("Python自動(dòng)化辦公實(shí)戰(zhàn).docx", "Python自動(dòng)化辦公實(shí)戰(zhàn).docx.pdf")
如果要對某個(gè)目錄下的 Word 批量轉(zhuǎn)換為 pdf,可以這樣:
from docx2pdf import convert
convert("目錄路徑/")
批量轉(zhuǎn)換為 pdf 時(shí)是否非常方便?
知道了這些小操作,就可以組裝大操作,比如后面可以用 Python 將 Word 轉(zhuǎn)換為 pdf 后作為附件發(fā)送郵件給其他人。
最后的話
本文分享了一種讀寫 Word 的方式,在日常工作中如果是重復(fù)性的 Word 操作,可考慮 Python 自動(dòng)化,有問題請留言交流。閱讀原文可以查看 gitee 上的代碼。
以上就是Python辦公自動(dòng)化解決world批量轉(zhuǎn)換的詳細(xì)內(nèi)容,更多關(guān)于Python辦公自動(dòng)化的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python實(shí)現(xiàn)求兩個(gè)字符串的最長公共子串方法
今天小編就為大家分享一篇python實(shí)現(xiàn)求兩個(gè)字符串的最長公共子串方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
python實(shí)現(xiàn)電子產(chǎn)品商店
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)電子產(chǎn)品商店,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02
Python Django項(xiàng)目和應(yīng)用的創(chuàng)建詳解
這篇文章主要為大家介紹了Python Django項(xiàng)目和應(yīng)用的創(chuàng)建,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2021-11-11
python數(shù)據(jù)分析之單因素分析線性擬合及地理編碼
這篇文章主要介紹了python數(shù)據(jù)分析之單因素分析線性擬合及地理編碼,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-06-06
Python使用re模塊實(shí)現(xiàn)正則表達(dá)式操作指南
在Python中需要通過正則表達(dá)式對字符串進(jìn)?匹配的時(shí)候,可以使??個(gè)python自帶的模塊,名字為re,下面這篇文章主要給大家介紹了關(guān)于Python使用re模塊實(shí)現(xiàn)正則表達(dá)式操作的相關(guān)資料,需要的朋友可以參考下2022-07-07
詳解python 拆包可迭代數(shù)據(jù)如tuple, list
拆包是指將一個(gè)結(jié)構(gòu)中的數(shù)據(jù)拆分為多個(gè)單獨(dú)變量中。下面通過本文給大家介紹python 拆包可迭代數(shù)據(jù)如tuple, list的相關(guān)資料,需要的朋友參考下吧2017-12-12
Python抓取移動(dòng)App數(shù)據(jù)使用mitmweb監(jiān)聽請求與響應(yīng)
這篇文章主要介紹了Python抓取移動(dòng)App數(shù)據(jù)使用mitmweb監(jiān)聽請求與響應(yīng),mitmproxy控制臺(tái)方式、mitmdump與Python對接的方式、mitmweb可視化方式,需要的朋友可以參考一下2022-01-01
python+html實(shí)現(xiàn)免費(fèi)在線行為驗(yàn)證保護(hù)賬號安全
這篇文章主要為大家介紹了python+html免費(fèi)在線行為驗(yàn)證保護(hù)賬號安全實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09

