Python - 使用 .docx 模組


Word 文件包含格式化的文字,包裹在三個物件級別中。最低級別- 執行物件、中間級別- 段落物件和最高級別- 文件物件。

因此,我們不能使用普通文字編輯器處理這些文件。但是,我們可以使用 python-docx 模組在 Python 中操縱這些 Word 文件。

  • 第一步是安裝這個第三方模組 python-docx。你可以使用 pip “pip install python-docx”
  • 安裝後匯入“docx”,而不是“python-docx”。
  • 使用“docx.Document”類開始處理 Word 文件。

示例

# import docx NOT python-docx
import docx
# create an instance of a word document
doc = docx.Document()
# add a heading of level 0 (largest heading)
doc.add_heading('Heading for the document', 0)
# add a paragraph and store
# the object in a variable
doc_para = doc.add_paragraph('Your paragraph goes here, ')
# add a run i.e, style like
# bold, italic, underline, etc.
doc_para.add_run('hey there, bold here').bold = True
doc_para.add_run(', and ')
doc_para.add_run('these words are italic').italic = True
# add a page break to start a new page
doc.add_page_break()
# add a heading of level 2
doc.add_heading('Heading level 2', 2)
# pictures can also be added to our word document
# width is optional
doc.add_picture('path_to_picture')
# now save the document to a location
doc.save('path_to_document')

更新於: 2020 年 8 月 8 日

已檢視 9K+ 次數

啟動你的 職業生涯

透過完成課程獲得證書

開始
廣告
© . All rights reserved.