docx模塊詳解-讀寫字體設置
二,相關概念
三,模塊的安裝和導入
四,讀取word文本
五,寫word文本
六,讀取表格
七,添加段落
八,docx模塊其它常用方法
一,docx模塊
Python可以利用python-docx模塊處理word文檔,處理方式是面向對象的。也就是說python-docx模塊會把word文檔,文檔中的段落、文本、字體等都看做對象,對對象進行處理就是對word文檔的內容處理。
# 下載docx包 pip install python-docx
二,相關概念
如果需要讀取word文檔中的文字(一般來說,程序也只需要認識word文檔中的文字信息),需要先了解python-docx模塊的幾個概念。
1,Document對象,表示一個word文檔。
2,Paragraph對象,表示word文檔中的一個段落
3,Paragraph對象的text屬性,表示段落中的文本內容。
三,模塊的安裝和導入
需要注意,python-docx模塊安裝需要在cmd命令行中輸入pip install python-docx,如下圖表示安裝成功(最后那句英文Successfully installed,成功地安裝完成)
注意在導入模塊時,用的是import docx。
from docx import Document from docx.enum.text import WD_ALIGN_PARAGRAPH #設置對象居中、對齊等。 from docx.enum.text import WD_TAB_ALIGNMENT,WD_TAB_LEADER #設置制表符等 from docx.shared import Inches #設置圖像大小 from docx.shared import Pt #設置像素、縮進等 from docx.shared import RGBColor #設置字體顏色 from docx.shared import Length #設置寬度
四,讀取word文本
# -*- conding:utf-8 -*-
import docx
file = docx.Document(r"D:\python從入門到放棄\7\2\files.docx")
print('段落:' + str(len(file.paragraphs)))
#
# for para in file.paragraphs:
# print(para.text)
for i in range(len(file.paragraphs)):
print("第" + str(i) + "段的內容是:" + file.paragraphs[i].text)
五,寫word文本
# -*- conding:utf-8 -*-
import sys
from docx import Document
from docx.shared import Inches
def main():
# reload(sys)
# sys.setdefaultencoding('utf-8')
# 創建文檔對象
document = Document()
# 設置文檔標題,中文要用unicode字符串
document.add_heading(u'我的一個新文檔', 0)
# 往文檔中添加段落
p = document.add_paragraph('This is a paragraph having some ')
p.add_run('bold ').bold = True
p.add_run('and some ')
p.add_run('italic.').italic = True
# 添加一級標題
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('cat.png', width=Inches(2.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().cells
new_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('demo1.doc')
if __name__ == '__main__':
main()
六,讀取表格
# -*- conding:utf-8 -*-
import docx
doc = docx.Document('wenjian.docx')
for table in doc.tables: # 遍歷所有表格
print('----table------')
for row in table.rows: # 遍歷表格的所有行
# row_str = '\t'.join([cell.text for cell in row.cells]) # 一行數據
# print row_str
for cell in row.cells:
print(cell.text, '\t', )
print() # 換行
七,添加段落
document=docx.Document() # 創建一個空白文檔
document.styles['Normal'].font.name = '宋體' # 設置西文字體
document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), '宋體') # 設置中文字體
p = document.add_paragraph() # 添加一個段落
p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY # 設置對齊方式
p.paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE # 設置行間距
p.paragraph_format.space_after = Pt(0) # 設置段后間距
run = p.add_run('content') # 延長段落
run.font.color.rgb = RGBColor(255, 0, 0) # 設置字體顏色
run.font.size = Pt(22) # 設置字號
run.font.bold = True # 設置下劃線
八,docx模塊其它常用方法
字號與磅值的關系
| 字號 | 磅值 |
|---|---|
| 八號 | 5 |
| 七號 | 5.5 |
| 小六 | 6.5 |
| 六號 | 7.5 |
| 小五 | 9 |
| 五號 | 10.5 |
| 小四 | 12 |
| 四號 | 14 |
| 小三 | 15 |
| 三號 | 16 |
| 小二 | 18 |
| 二號 | 22 |
| 小一 | 24 |
| 一號 | 26 |
| 小初 | 36 |
| 初號 | 42 |
新增頁眉
section=document.sections[0] header=section.header bt1=header.paragraphs[0] bt1.text='此處是頁眉1'
新增頭信息
t1=document.add_paragraph('此處Tetle信息','Title')
新增段落 及 向前插入段落
p1=document.add_paragraph('新增段落P1')
pin1=p1.insert_paragraph_before('在p1前插入段落pin1')
段落里設置參數樣式 或 指定.style來設置參數
p2=document.add_paragraph('新增段落p2并設置style類型',style='ListBullet')
p3=document.add_paragraph('新增段落p3并指定style類型')
p3.style='ListBullet'
添加標題 可設置標題級別1-9
h1=document.add_heading('此處默認標題1')
h2=document.add_heading('此處添加標題2',level=2)
h3=document.add_heading('此處添加標題3',level=3)
設置字體
通過.add_run來設置字體: 加粗、斜體、大小、顏色、下劃線
paragraph=document.add_paragraph()
r1=paragraph.add_run('通過.bold=True來設置粗體')
r1.bold=True
r1.style='Emphasis'
r2=paragraph.add_run('也可以')
r3=paragraph.add_run('\n通過.italic=True來設置斜體,\n通過.font.size來設置字體大小,\n通過.font.color.rgb=RGBColor來設置字體顏色')
r3.italic=True
r3.font.size=Pt(20)
r3.font.color.rgb=RGBColor(200,77,150)
| 方法 | 作用 |
|---|---|
| all_caps | 全部大寫字母 |
| bold | 加粗 |
| color | 字體顏色 |
| complex_script | 是否為“復雜代碼” |
| cs_bold | “復雜代碼”加粗 |
| cs_italic | “復雜代碼”斜體 |
| double_strike | 雙刪除線 |
| emboss | 文本以凸出頁面的方式出現 |
| hidden | 隱藏 |
| imprint | 印記 |
| italic | 斜體 |
| name | 字體 |
| no_proof | 不驗證語法錯誤 |
| outline | 顯示字符的輪廓 |
| shadow | 陰影 |
| small_caps | 小型大寫字母 |
| snap_to_grid | 定義文檔網格時對齊網絡 |
| strike | 刪除線 |
| subscript | 下標 |
| superscript | 上標 |
| underline | 下劃線 |
設置居中、左右對齊、縮進、制表符
p4=document.add_paragraph('準備開始設置居中、左右對齊、縮進等')
p4.paragraph_format.alignment=WD_ALIGN_PARAGRAPH.CENTER
| 方法 | 作用 |
|---|---|
| LEFT | 左對齊 |
| CENTER | 文字居中 |
| RIGHT | 右對齊 |
| JUSTIFY | 本兩端對齊 |
設置縮進
默認Inches(0.5)等于四個空格
p5=document.add_paragraph('content')
p5.paragraph_format.left_indent=Inches(0.5)
設置首行縮進
p5.paragraph_format.first_line_indent=Inches(0.5)
設置段落間距 分為段落前 和 段落后
p5.paragraph_format.space_before=Pt(30) p5.paragraph_format.space_after=Pt(12)
設置段落行距當行距為最小值和固定值時,設置值單位是磅,用Pt;當行間距為多倍行距時,設置值為數值。
p5.paragraph_format.line_spacing=Pt(30)
| 方法 | 作用 |
|---|---|
| SINGLE | 單倍行距(默認) |
| ONE_POINT_FIVE | 1.5倍行距 |
| DOUBLE | 2倍行距 |
| AT_LEAST | 最小值 |
| EXACTLY | 固定值 |
| MULTIPLE | 多倍行距 |
paragraph.line_spacing_rule = WD_LINE_SPACING.EXACTLY #固定值 paragraph_format.line_spacing = Pt(18) # 固定值18磅 paragraph.line_spacing_rule = WD_LINE_SPACING.MULTIPLE #多倍行距 paragraph_format.line_spacing = 1.75
分頁屬性
p5.paragraph_format.keep_with_next = True
| 方法 | 作用 | 說明 |
|---|---|---|
| widow_control | 孤行控制 | 防止在頁面頂端單獨打印段落末行或在頁面底端單獨打印段落首行 |
| keep_with_next | 與下段同頁 | 防止在選中段落與后面一段間插入分頁符 |
| page_break_before | 段前分頁 | 在選中段落前插入分頁符 |
| keep_together | 段中不分頁 | 防止在段落中出現分頁符 |
添加分頁符
document.add_page_break()
p5=document.add_paragraph('.add_page_break()硬分頁,即使文本未滿')
添加表格、設置表格樣式
table=document.add_table(rows=2,cols=2) table.style='LightShading-Accent1'
選擇表格內單元格、單元格賦值添加和改變內容
cell=table.cell(0,1) cell.text='通過cell.text()來添加內容'
選擇表格的行,通過索引,然后索引單元格
row=table.rows[1] row.cells[0].text='通過.add_table(,)來添加表格' row.cells[1].text='通過for row in table.rows內嵌套 for cell in row.cells來循環輸出表格內容'
for循環逐行輸出表格內容
for row in table.rows:
for cell in row.cells:
print(cell.text)
len表格內行列數
row_count=len(table.rows) col_count=len(table.columns) print(row_count,col_count,'現表格行列數') row=table.add_row() #逐步添加行 print(len(table.rows),len(table.columns),'添加后表格行列數')
添加另一個表格 及 指定表格樣式
table1=document.add_table(1,3) table1.style='LightShading-Accent2' #設置表格樣式
填充 標題行
heading_cells=table1.rows[0].cells #獲取 行列標 heading_cells[0].text='Qtx' #為行列表內的cell單元格 賦值 heading_cells[1].text='Sku' heading_cells[2].text='Des'
表格數據
items=( (7,'1024','plush kitens'), (3,'2042','furbees'), (1,'1288','french poodle collars,deluxe') )
為每個項目添加數據行
for item in items:
cells=table1.add_row().cells
cells[0].text=str(item[0])
cells[1].text=str(item[1])
cells[2].text=str(item[2])
添加圖片
document.add_picture('002592.png',width=Inches(2))
調整圖片大小,如下:
document.add_picture('demo.png', width=Inches(1.0), height=Inches(1.0))
若同時定義寬度和高度,則圖片會被拉伸或壓縮到指定大小;若僅定義寬度或高度,則圖會自適應調整大小。
保存文檔
document.save('test.docx')
end

浙公網安備 33010602011771號