python 對word文件進行操作


1.利用pip安裝pyhton-docx

原文連接

直接是用pip install  python_docx是不行的  

需要去手動下載https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient

然后再將本地的安裝包安裝

 

寫入word文檔:

#coding=utf-8

from 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().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'測試.docx')

讀取word文檔:

 

#coding=utf-8

from 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',
        print
    print '\n'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM