Python 操作 Word用 docx 模塊讀取 Worddocx 安裝cmd 中輸入pip install python-docx 即可安裝 docx 模塊 docx 常用函數創(chuàng)建空白文檔from docx import Document
document = Document()document.save("word.docx") # 生成空白 wordprint(document) ![[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-Xo1siDkz-1637387517723)(python辦公自動化.assets/image-20211119225443886.png)]](http://image109.360doc.com/DownloadImg/2021/11/3009/235043155_1_20211130094715317)
讀取文檔document = Document("word.docx") # 讀取現有的 word 建立文檔對象 ![[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-dST0hckl-1637387517728)(python辦公自動化.assets/image-20211119225308276.png)]](http://image109.360doc.com/DownloadImg/2021/11/3009/235043155_2_20211130094715505)
獲取文檔段落from docx import Document
document = Document("word.docx") # 讀取現有的 word 對象all_paragraphs = document.paragraphsprint(type(all_paragraphs))for paragraph in all_paragraphs:
# print(paragraph.paragraph_format) # 打印出word中每段的樣式名稱
# 打印每一個段落的文字
print(paragraph.text)
# 循環(huán)讀取每個段落里的run內容# 一個run對象是相同樣式文本的延續(xù)for paragraph in all_paragraphs:
for run in paragraph.runs:
print(run.text) # 打印run內容 
from docx import Documentfrom docx.shared import Pt, RGBColor
document = Document() # 讀取現有的 word 建立文檔對象# 二、寫入內容# 段落p1 = document.add_paragraph("早睡早起!?。?quot;)format_p1 = p1.paragraph_format# 左右縮進format_p1.left_indent = Pt(20)format_p1.right_indent = Pt(20)# 首行縮進format_p1.first_line_indent = Pt(20)# 行間距format_p1.line_spacing = 1# 追加# 一個run對象是相同樣式文本的延續(xù)run = p1.add_run("我也想做癩皮狗\n")# 字體,字號,文字顏色run.font.size = Pt(12)run.font.name = "微軟雅黑"run.font.color.rgb = RGBColor(235, 123, 10)run1 = p1.add_run("賈某人不學習")# 加粗,下劃線,斜體run1.bold = Truerun1.font.underline = Truerun1.font.italic = True# # 三、保存文件document.save("word.docx")all_paragraphs = document.paragraphs# print(type(all_paragraphs))#,打印后發(fā)現是列表# 是列表就開始循環(huán)讀取dfor paragraph in all_paragraphs:
# print(paragraph.paragraph_format) # 打印出word中每段的樣式名稱
# 打印每一個段落的文字
print(paragraph.text)
# 循環(huán)讀取每個段落里的run內容
# for run in paragraph.runs:
# print(run.text) # 打印run內容 
Word 寫入操作from docx import Documentfrom docx.shared import Pt, RGBColor
document = Document() # 讀取現有的 word 建立文檔對象# 二、寫入內容document.add_heading("python 操作 Word")# 段落p1 = document.add_paragraph("早睡早起?。?!")p1.insert_paragraph_before("Power!??!")format_p1 = p1.paragraph_format# 左右縮進format_p1.left_indent = Pt(20)format_p1.right_indent = Pt(20)# 首行縮進format_p1.first_line_indent = Pt(20)# 行間距format_p1.line_spacing = 1# 追加# 一個run對象是相同樣式文本的延續(xù)run = p1.add_run("我也想做癩皮狗\n")# 字體,字號,文字顏色run.font.size = Pt(12)run.font.name = "微軟雅黑"run.font.color.rgb = RGBColor(235, 123, 10)run1 = p1.add_run("賈某人不學習")# 加粗,下劃線,斜體run1.bold = Truerun1.font.underline = Truerun1.font.italic = True# # 三、保存文件document.save("word.docx")all_paragraphs = document.paragraphs# print(type(all_paragraphs))#,打印后發(fā)現是列表# 是列表就開始循環(huán)讀取dfor paragraph in all_paragraphs:
# print(paragraph.paragraph_format) # 打印出word中每段的樣式名稱
# 打印每一個段落的文字
print(paragraph.text)
# 循環(huán)讀取每個段落里的run內容
# for run in paragraph.runs:
# print(run.text) # 打印run內容 
|