Python 读写word
生活随笔
收集整理的這篇文章主要介紹了
Python 读写word
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#coding=utf-8from docx import Document
from docx.shared import Pt
from docx.shared import Inches
from docx.oxml.ns import qn
#打開文檔
document = Document()
#加入不同等級的標題
document.add_heading(u'MS WORD寫入測試',0)
document.add_heading(u'一級標題',1)
document.add_heading(u'二級標題',2)
#添加文本
paragraph = document.add_paragraph(u'我們在做文本測試!')
#設置字號
run = paragraph.add_run(u'設置字號、')
run.font.size = Pt(24)#設置字體
run = paragraph.add_run('Set Font,')
run.font.name = 'Consolas'#設置中文字體
run = paragraph.add_run(u'設置中文字體、')
run.font.name=u'宋體'
r = run._element
r.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')#設置斜體
run = paragraph.add_run(u'斜體、')
run.italic = True#設置粗體
run = paragraph.add_run(u'粗體').bold = True#增加引用
document.add_paragraph('Intense quote', style='Intense Quote')#增加無序列表
document.add_paragraph(u'無序列表元素1', style='List Bullet'
)
document.add_paragraph(u'無序列表元素2', style='List Bullet'
)
#增加有序列表
document.add_paragraph(u'有序列表元素1', style='List Number'
)
document.add_paragraph(u'有序列表元素2', style='List Number'
)
#增加圖像(此處用到圖像image.bmp,請自行添加腳本所在目錄中)
document.add_picture('image.bmp', width=Inches(1.25))#增加表格
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Name'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
#再增加3行表格元素
for i in xrange(3):row_cells = table.add_row().cellsrow_cells[0].text = 'test'+str(i)row_cells[1].text = str(i)row_cells[2].text = 'desc'+str(i)#增加分頁
document.add_page_break()#保存文件
document.save(u'測試.docx')
?
#coding=utf-8from docx import Document #打開文檔 document = Document(u'測試.docx') #讀取每段資料 l = [ paragraph.text.encode('gb2312') for paragraph in document.paragraphs]; #輸出并觀察結果,也可以通過其他手段處理文本即可 for i in l:print i #讀取表格材料,并輸出結果 tables = [table for table in document.tables]; for table in tables:for row in table.rows:for cell in row.cells:print cell.text.encode('gb2312'),'\t',printprint '\n'?
總結
以上是生活随笔為你收集整理的Python 读写word的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 03-HTML-图片标签
- 下一篇: Python字典列表