cmd 中輸入pip install python-docx
即可安裝 docx
模塊
from docx import Document document = Document()document.save("word.docx") # 生成空白 wordprint(document)
document = Document("word.docx") # 讀取現有的 word 建立文檔對象
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) # 循環讀取每個段落里的run內容# 一個run對象是相同樣式文本的延續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("早睡早起!!!")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對象是相同樣式文本的延續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))#,打印后發現是列表# 是列表就開始循環讀取dfor paragraph in all_paragraphs: # print(paragraph.paragraph_format) # 打印出word中每段的樣式名稱 # 打印每一個段落的文字 print(paragraph.text) # 循環讀取每個段落里的run內容 # for run in paragraph.runs: # print(run.text) # 打印run內容
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對象是相同樣式文本的延續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))#,打印后發現是列表# 是列表就開始循環讀取dfor paragraph in all_paragraphs: # print(paragraph.paragraph_format) # 打印出word中每段的樣式名稱 # 打印每一個段落的文字 print(paragraph.text) # 循環讀取每個段落里的run內容 # for run in paragraph.runs: # print(run.text) # 打印run內容