Python之word文档编写

# -*- coding: utf-8 -*-
from docx import Document
from docx.shared import Inches,Pt,RGBColor
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT

#创建文档
doc=Document()
#添加标题,0表示样式为title
doc.add_heading('标题',0)
#添加段落
p=doc.add_paragraph('第一段落')
#段落 p 后面添加内容
p.add_run('添加内容1').bold=True
p2=p.add_run(' 添加内容2 ')
#设置字体
p2.style.font.name='黑体'
#设置字体颜色
p2.font.color.rgb=RGBColor(255,0,0)
p.add_run('添加内容3.').italic=True
#添加标题1
doc.add_heading('标题1',level=1)
#添加段落,设置样式
'''
#查看样式
for s in Document().styles:
    print(s)
'''
doc.add_paragraph('第二段落',style='Intense Quote')

#添加标题2
h2=doc.add_heading('标题2')
#设置字体样式
h2.style.font.size=Pt(25)
#设置字体颜色
h2.style.font.color.rgb=RGBColor(97,197,84)
#设置文字居中
h2.paragraph_format.alignment=WD_PARAGRAPH_ALIGNMENT.CENTER


#添加图片,设置宽度
doc.add_picture('xx.png',width=Inches(1.25))
#添加分页
doc.add_page_break()
#添加表格
table=doc.add_table(rows=1,cols=3,style='Table Grid')
t_cells=table.rows[0].cells
t_cells[0].text='s1'
t_cells[1].text='s2'
t_cells[2].text='s3'
#新增行
#table.add_row().cells
#table.cell(1,1).text=table.cell(0,0).text
#table.rows[1].cells[1].text
#table.columns[1].cells[1].text
r_rows=table.add_row().cells
r_rows[0].text='x'
#设置单元格垂直对齐方式(TOP/BOTTOM/CENTER)
table.cell(1,1).vertical_alignmen=WD_CELL_VERTICAL_ALIGNMENT.CENTER
#遍历行
for row in table.rows:
    #设置行高
    row.height=Pt(50)
    #获取行号
    print(row._index)

#合并单元格
cell01=table.cell(0,1)
cell02=table.cell(0,2)
cell01.merge(cell02)


#保存文档
doc.save('dd.docx')
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值