国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

用python處理MS Word的實(shí)例講解

2020-02-23 00:03:16
字體:
供稿:網(wǎng)友

使用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'            
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 长沙市| 博爱县| 政和县| 常宁市| 乌鲁木齐县| 广南县| 天津市| 芮城县| 榆社县| 吉木萨尔县| 石家庄市| 大兴区| 孝义市| 额敏县| 肥西县| 五大连池市| 临邑县| 义乌市| 建德市| 河北区| 南康市| 定结县| 洛阳市| 彩票| 朔州市| 安陆市| 莆田市| 永平县| 东海县| 新干县| 铜鼓县| 安泽县| 宁陕县| 汉寿县| 视频| 开阳县| 白城市| 正安县| 洛扎县| 木里| 瑞安市|