网上抄来抄去,拼了一些常用的用法。
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.shared import Inches
document = Document()
for i in range(3):
document.add_heading('我是标题', i)
p = document.add_paragraph('我是段落!!') # 这里是添加一个段落
p.add_run('加粗').bold = True # 这里是在这个段落p里文字some后面添加bold字符
p.add_run('——段落后加别的——')
p.add_run('斜体').italic = True
p.italic = True
p = document.add_paragraph('')
p.add_run('123', style="Heading 1 Char")
p.add_run('456')
p.add_run('789', style="Heading 2 Char")
p = document.add_paragraph('')
run = p.add_run('Set Font')
run.font.name = ('Consolas')
for i in range(10,30,4):
p = document.add_paragraph('')
run = p.add_run('设置字号及字体'+str(i))
run.font.size = Pt(i)
run.font.name = ''
r = run._element
r.rPr.rFonts.set(qn('w:eastAsia'),'幼圆')
document.add_paragraph('Intense quote', style='Intense Quote')
#增加有序列表
document.add_paragraph(
u'有序列表元素1',style='List Number'
)
document.add_paragraph(
u'有序列别元素2',style='List Number'
)
#增加无序列表
document.add_paragraph(
u'无序列表元素1',style='List Bullet'
)
document.add_paragraph(
u'无序列表元素2',style='List Bullet'
)
#增加图片(此处使用相对位置)
document.add_picture(r'd:\test.png',width=Inches(3))
#增加分页
document.add_page_break()
#增加表格
table = document.add_table(rows=4,cols=4)
hdr_cells=table.rows[0].cells
hdr_cells[0].text="第一列"
hdr_cells[1].text="第二列"
hdr_cells[2].text="第三列"
document.add_paragraph()
table2 = document.add_table(rows = 5,cols = 5,style = 'Table Grid')
table2.autofit = False
for rows in table2.rows:
for cells in rows.cells:
cells.text = 'test'
table2.columns.width = Inches(0.55) #这一行设置表格宽度的没有起作用,不知道什么原因。
document.save(r'd:\test.docx')