python办公自动化之word写入

学习目标:

掌握python对word的基本操作

学习内容:

1.word写入
2.写入表格和图片
3.设置word样式

学习时间:

例如: 2021-03-29 20:00

学习记录:

1.安装第三方模块

  pip install python-docx

github官方手册:https://python-docx.readthedocs.io/en/latest/

2.段落写入

from docx import Document
#https://python-docx.readthedocs.io/en/latest/
#1.创建一个word文档对象
from docx.shared import Pt, RGBColor

document = Document()
#读取指定word文档对象  document = Document('info.docx')
#2.写入word内容
header = document.add_heading('早读|养老金将实现连续17年上涨',level=2)
headerFormate = header.paragraph_format
headerFormate.alignment = 1 # 0 左对齐 1 文本居中对齐 2 右对齐
#插入文档段落
p1 = document.add_paragraph('国务院近日印发关于落实政府工作报告重点工作分工的意见,指明44项重点工作的分工责任及完成时限。其中,有6项社保相关政策明确了时间安排。这意味着,你我的社保将迎来多种新变化、获得多项新福利。')
#设置缩进
foramte = p1.paragraph_format
#设置左右缩进
foramte.left_indent = Pt(20)
foramte.right_indent = Pt(20)
#设置所行缩进
foramte.first_line_indent = Pt(20)
run1 = p1.add_run('根据政府工作报告安排,居民医保和基本公共卫生服务经费人均财政补助标准分别再增加30元和5元。')
run1.bold = True
run1.font.underline = True
run1.font.size = Pt(15)
run1.font.color.rgb = RGBColor(235,34,23)
#设置行间距

#3.保存word文档对象
document.save('info.docx')

在这里插入图片描述

3向word中插入图片和表格

from docx import  Document
from docx.shared import Pt

document = Document()
#插入小姐姐图片
document.add_picture('sister.jpg')
#指定图片宽度和高度
document.add_picture('sister.jpg',Pt(300),Pt(400))

#写入表格数据
table = document.add_table(rows=1,cols=3)
header_cell = table.rows[0].cells
header_cell[0].text = '月份'
header_cell[1].text = '预期销售额'
header_cell[2].text = '实际销售额'

data = (
    ['一月份',340,435,879],
    ['二月份', 540, 445, 879],
    ['三月份', 650, 535, 879],
)
for item in data :
    #获取表格单元格的所有数据
    row_cells = table.add_row().cells
    print(row_cells)
    row_cells[0].text = item[0]
    row_cells[1].text = str(item[1])
    row_cells[2].text = str(item[2])

#打印总行数
print(len(document.tables[0].rows))
#保存word
document.save('text.docx')

在这里插入图片描述

4.设置word样式

from  docx import  Document
from  docx.enum.style import WD_STYLE_TYPE
from docx.shared import Pt

document = Document()
#设置样式
style = document.styles.add_style('textStyle',WD_STYLE_TYPE.PARAGRAPH)
style.font.size = Pt(20)
style.font.bold = True
p = document.add_paragraph('世界那么大,我想出去看一看',style='textStyle')
document.save('style.docx')

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值