日常上官網?https://python-docx.readthedocs.io/en/latest/
一、安裝
pip install python-docx
二、寫入word
word 中主要有兩種用文本格式等級:塊等級(block-level)和內聯等級(inline-level)word 中大部分內容都是由這兩種等級的對象組成的(其他的諸如眉頁、引腳等,docx 庫的作者還在開發中)
塊等級(block-level):也就是段落
塊對象一般包括:段落(paragraph)、圖片(inline picture)、表(table)、標題(heading)、有序列表(numbered lists)、無序列表(bullets?lists)
段落是 word 文件中的主要塊對象(block-level object),塊等級項(block-level item)主要任務是將文本格式從左邊界向右邊界展示(flows);對于段落而言,邊界就是分段標識,或者是文本的列邊界,列表(table)也是塊對象(block-level object)
內聯等級(inline-level):也就是字體
內聯對象(inline-level object)是塊對象(block-level object)的組成部分,塊對象的所有內容都包含在內聯對象中,一個塊對象由一個或多個內聯對象組成,run 是常用的內聯對象,例如:
p = document.add_paragraph('This is paragraph')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
這個例子中一個段落(塊對象)包含三個 run(內聯對象),每一個 run 都設置有不同屬性
寫word示例:
# coding:utf-8
import sysfrom docx import Document
from docx.shared import Inchesdef main():reload(sys)sys.setdefaultencoding('utf-8')# 創建文檔對象document = Document()# 新增樣式(第一個參數是樣式名稱,第二個參數是樣式類型:1代表段落;2代表字符;3代表表格)style = doc.styles.add_style('style name 1', 2)# 從樣式庫中選取 'Normal' 樣式,并設置 'Normal' 樣式的字符屬性(font)style = document.styles['Normal']style.font.name = "Microsoft YaHei UI"style.font.size = Pt(50)# 將設置好字符屬性的樣式運用到段落中# p = document.add_paragraph("change font attribution", style = 'Normal')# 從樣式庫中選取 'Heading 2'' 樣式,并設置段落格式(paragraph format)style = document.styles['Heading 2']style.paragraph_format.left_indent = Pt(20)style.paragraph_format.widow_control = True# 將設置好段落格式的 style 運用到段落中# p = document.add_paragraph('This is Heading, level 1', style = style)# 設置文檔標題,中文要用unicode字符串document.add_heading(u'我的一個新文檔',0)from docx.shared import RGBColor,Inches,Ptfrom docx.enum.text import WD_ALIGN_PARAGRAPH# 往文檔中添加段落p = document.add_paragraph('This is a paragraph having some ')p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER # WD_ALIGN_PARAGRAPH.LEFT,左對齊;WD_ALIGN_PARAGRAPH.RIGHT,右對齊p.paragraph_format.left_indent = Inches(0.5) # 設置段落從左開始縮進,使用Inches來衡量p.paragraph_format.right_indent = Pt(20) # 設置段落從右開始縮進,使用Pt來衡量p.paragraph_format.first_line_indent = Inches(0.5) # 設置段落第一行縮進,可以與上兩個縮進疊加p.paragraph_format.space_after = Pt(5) # 設置與上一段間隔 Pt(5)p.paragraph_format.space_before = Pt(10) # 設置與下一段間隔 Pt(10)p.paragraph_format.line_spacing = Pt(18) # 行距p_run = p.add_run('xxx')p_run.font.italic = True # 設置為斜體p_run.font.size = Pt(12) # 設置字體大小p_run.font.color.rgb = RGBColor(0, 0, 0) # 設置字體顏色p_run.font.name = u"宋體" # 設置字體樣式p_run.font._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體') # 設置字體樣式p_run.font.underline = False # 不設置下劃線p_run.font.bold = None # 設置粗體為繼承上一個字體的格式# 這一類屬性,每個有三種狀態:True 為使用屬性;False 為不使用屬性;None 默認屬性繼承自上一個字體# 添加一級標題document.add_heading(u'一級標題, level = 1',level = 1)document.add_paragraph('Intense quote',style = 'IntenseQuote')# 添加無序列表document.add_paragraph('first item in unordered list',style = 'ListBullet')# 添加有序列表document.add_paragraph('first item in ordered list',style = 'ListNumber')document.add_paragraph('second item in ordered list',style = 'ListNumber')document.add_paragraph('third item in ordered list',style = 'ListNumber')# 添加圖片,并指定寬度document.add_picture('e:/docs/pic.png',width = Inches(1.25))# 添加表格: 1行3列table = document.add_table(rows = 1,cols = 3)# 獲取第一行的單元格列表對象hdr_cells = table.rows[0].cells# 為每一個單元格賦值,值都要為字符串類型hdr_cells[0].text = 'Name'hdr_cells[1].text = 'Age'hdr_cells[2].text = 'Tel'# 為表格添加一行new_cells = table.add_row().cellsnew_cells[0].text = 'Tom'new_cells[1].text = '19'new_cells[2].text = '12345678'# 添加分頁符document.add_page_break()# 往新的一頁中添加段落p = document.add_paragraph('This is a paragraph in new page.')# 保存文檔document.save('e:/docs/demo1.docx')if __name__ == '__main__':main()
運行程序會得到一個下面的文檔
三、讀文檔?
對于文件名是中文的讀取時會報錯
- doc.paragraphs??# 段落集合
- doc.tables? ? ? ? ??# 表格集合
- doc.sections? ? ? # 節??集合
- doc.styles? ? ? ? ? # 樣式集合
- doc.inline_shapes?# 內置圖形?等等...
讀取已有的word文檔示例
# coding:utf-8
import sysfrom docx import Documentdef main():reload(sys)sys.setdefaultencoding('utf-8')# 創建文檔對象,寫自己的 word 路徑document = Document('e:/docs/demo2.docx')# 讀取文檔中所有的段落列表ps = document.paragraphs# 每個段落有兩個屬性:style和textps_detail = [(x.text,x.style.name) for x in ps]with open('out.tmp','w+') as fout:fout.write('')# 讀取段落并寫入一個文件with open('out.tmp','a+') as fout:for p in ps_detail:fout.write(p[0] + '\t' + p[1] + '\n\n')# 讀取文檔中的所有段落的列表tables = document.tables# 遍歷table,并將所有單元格內容寫入文件中with open('out.tmp','a+') as fout:for table in tables:for row in table.rows:for cell in row.cells:fout.write(cell.text + '\t')fout.write('\n')if __name__ == '__main__':main()
四、其他事項
1、如果段落中是有超鏈接的,那么段落對象是讀取不出來超鏈接的文本的,需要把超鏈接先轉換成普通文本,方法:全選word文檔的所有內容,按快捷鍵Ctrl+Shift+F9即可。
2、讀取某些文件時會報錯,docx.opc.exceptions.PackageNotFoundError: Package not found。原因:docx無法識別doc,需要先手動或者使用win32com轉換
from win32com import client as wc
import docxdef doSaveAas():word = wc.Dispatch('Word.Application')doc = word.Documents.Open(u'E:\old.doc') # 目標路徑下的文件doc.SaveAs(u'E:\\new_path.docx', 12, False, "", True, "", False, False, False, False) # 轉化后路徑下的文件 doc.Close()word.Quit()doSaveAas()
鏈接https://www.cnblogs.com/jiayongji/p/7290410.html