使用python工具讀寫MS Word文件(docx與doc文件),主要利用了python-docx包。本文給出一些常用的操作,并完成一個(gè)樣例,幫助大家快速入手。
安裝
pyhton處理docx文件需要使用python-docx 包,可以利用pip工具很方便的安裝,pip工具在python安裝路徑下的Scripts文件夾中
pip install python-docx
當(dāng)然你也可以選擇使用easy_install或者手動(dòng)方式進(jìn)行安裝
寫入文件內(nèi)容
此處我們直接給出一個(gè)樣例,根據(jù)自己的需要摘取有用的內(nèi)容
#coding=utf-8from docx import Documentfrom docx.shared import Ptfrom docx.shared import Inchesfrom docx.oxml.ns import qn#打開文檔document = Document()#加入不同等級(jí)的標(biāo)題document.add_heading(u'MS WORD寫入測(cè)試',0)document.add_heading(u'一級(jí)標(biāo)題',1)document.add_heading(u'二級(jí)標(biāo)題',2)#添加文本paragraph = document.add_paragraph(u'我們?cè)谧鑫谋緶y(cè)試!')#設(shè)置字號(hào)run = paragraph.add_run(u'設(shè)置字號(hào)、')run.font.size = Pt(24)#設(shè)置字體run = paragraph.add_run('Set Font,')run.font.name = 'Consolas'#設(shè)置中文字體run = paragraph.add_run(u'設(shè)置中文字體、')run.font.name=u'宋體'r = run._elementr.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')#設(shè)置斜體run = paragraph.add_run(u'斜體、')run.italic = True#設(shè)置粗體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,請(qǐng)自行添加腳本所在目錄中)document.add_picture('image.bmp', width=Inches(1.25))#增加表格table = document.add_table(rows=1, cols=3)hdr_cells = table.rows[0].cellshdr_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().cells row_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'測(cè)試.docx')該段代碼生成的文檔樣式如下

注:有一個(gè)問題沒找到如何解決,即如何為表格設(shè)置邊框線。如果您知道,還請(qǐng)能夠指教。
讀取文件內(nèi)容
#coding=utf-8from docx import Document#打開文檔document = Document(u'測(cè)試.docx')#讀取每段資料l = [ paragraph.text.encode('gb2312') for paragraph in document.paragraphs];#輸出并觀察結(jié)果,也可以通過其他手段處理文本即可for i in l: print i#讀取表格材料,并輸出結(jié)果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', print print '/n'
新聞熱點(diǎn)
疑難解答
圖片精選