1. 程式人生 > 其它 >Python向Word文件中寫入內容

Python向Word文件中寫入內容

#coding=utf-8
from docx import Document
from docx.shared import Pt
from docx.shared import Inches
from docx.oxml.ns import qn
#開啟文件
from urllib3.connectionpool import xrange

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')

  

原文連結: https://www.cnblogs.com/1gaoyu/p/12656003.html