1. python-docx模块

  • word的自动化
  • 针对手动创建批量制式Word文件、修改现有大量word文件存在的共性问题
  • python-docx是第三方模块,用于自动化生成和修改word文档
from docx import Document
from docx.shared import Pt,RGBColor
from docx.enum.style import  WD_STYLE_TYPE# Word文档字体和Pt字体大小的对照表
# 八号    5
# 七号    5.5
# 小六    6.5
# 六号    7.5
# 小五    9
# 五号    10.5
# 小四    12
# 四号    14
# 小三    15
# 三号    16
# 小二    18
# 二号    22
# 小一    24
# 一号    26
# 小初    36
# 初号    42# 1. 创建一个文档对象document = Document() #新建文档对象
# Document('已经存在的.docx')#读取已经存在的文档# 2. 写入内容
document.add_heading('我爱你', level=2) # 标题,级别为h2# word文档的样式处理(可以统一样式)[内置样式或者自定义样式]
style = document.styles.add_style('textstyle', WD_STYLE_TYPE.PARAGRAPH)
# print(style.style_id)
# print(style.name)
style.font.size = Pt(5)#删除样式
# document.styles['textstyle'].delete()# 段落
p1 = document.add_paragraph('我爱你,像风走过了3000里! 如果某一天,你不喜欢我了,我希望先开口的人是我,而不是你。渣男不渣,只是他们的心碎成了很多片。',style='textstyle')
p1.insert_paragraph_before("baby, i want to say you :")
format = p1.paragraph_format
format.left_indent = Pt(20) # 缩进
format.right_indent = Pt(20) # 缩进
# 首行缩进
format.first_line_indent = Pt(20)
#设置行间距
format.line_spacing = 1.5#追加段落
run = p1.add_run('耳旁软语是你,声嘶力竭也是你。爱的是你,离开的也是你。曾共度两三年的是你,而今老死不相往来也是你。')
run.font.size = Pt(12)
run.font.name = '微软雅黑'
run.font.color.rgb=RGBColor(235,33,24)run1 = p1.add_run('只要最后是你就好。')
run1.bold = True
run1.font.underline = True
run1.font.italic = True# 插入图片(指定宽高)
document.add_picture('plant.png', Pt(20), Pt(30))# 插入表格
table = document.add_table(rows=1, cols=3, style='Medium List 1') #表格样式这里我使用的是内置样式,可以查阅官方文档
# 构建表格
header_cells = table.rows[0].cells
header_cells[0].text = '地区'
header_cells[1].text = '最低彩礼'
header_cells[2].text = '最高彩礼'
# 为表格插入数据
data =(["四川", 5, 15],["江西", 30, 50],["乐山", 0, 10],
)
for item in data:rows_cells = table.add_row().cells # 添加并构建表格rows_cells[0].text = str(item[0])rows_cells[1].text = str(item[1])rows_cells[2].text = str(item[2])# 获取word文档中的表格
print(len(document.tables[0].rows)) # 打印总行数
print(len(document.tables[0].columns)) # 打印总列数
#cell
print(document.tables[0].cell(0,2).text)#获取表格第一行第3列的内容# 3. 保存文档
document.save('test.docx')

2. docx2pdf模块

word转换为pdf

from docx2pdf import convert
import pdfkit
import oscurrentDir = os.getcwd()
convert(input_path = currentDir + r"\test.docx", output_path = currentDir + r"\test.pdf")

第二种Word转换为pdf的方法

from win32com.client import constants, gencache
import os# 单个文件的转换
def createPdf(wordPath, pdfPath):word = gencache.EnsureDispatch("Word.Application") # 创建Word程序对象doc = word.Documents.Open(wordPath, ReadOnly=1) # 读取word文件# 转换方法doc.ExportAsFixedFormat(pdfPath, constants.wdExportFormatPDF) # 更多信息访问office开发人员中心文档word.Quit()# createPdf('E:\PycharmProjects\WorkAuto\yinlei.docx','E:\PycharmProjects\WorkAuto\yinlei.pdf' )# 多个文件的转换
# print(os.listdir('.')) #当前文件夹下的所有文件
wordfiles = []
for file in os.listdir('.'):if file.endswith(('.doc','.docx')):wordfiles.append(file)# print(wordfiles)
for file in wordfiles:filepath = os.path.abspath(file)index = filepath.rindex('.')pdfpath = filepath[:index]+'.pdf'createPdf(filepath, pdfpath)

3. python-pptx模块

  • 针对批量PPT的创建和修改i、大量图片、文字的写入、准确无误的插入图标等数据
  • python-pptx是第三方模块、自动生成和更新PowerPoint(.pptx)文件
import pptx
from pptx.util import Inches, Pt  # 英寸
from pptx.enum.shapes import MSO_SHAPE
from pptx.dml.color import RGBColorfrom pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.enum.chart import XL_LEGEND_POSITION
# 步骤:
# 1. 得到演示文稿的对像
prs = pptx.Presentation()
# 修改现有的ppt文件Presentation('xxx.pptx')# 2. 写入操作
slide = prs.slides.add_slide(prs.slide_layouts[0]) #插入一张幻灯片 slide_layouts是微软ppt软件内置的ppt模板集合,通过索引访问具体使用哪个内置模板
prs.slides.add_slide(prs.slide_layouts[1])
prs.slides.add_slide(prs.slide_layouts[2])# 删除幻灯片
print(len(prs.slides))
del prs.slides._sldIdLst[1]
print(len(prs.slides))# 给某个幻灯片操作
text1 = slide.shapes.add_textbox(Inches(5),Inches(5),Inches(5),Inches(5))
text1.text = 'i am yinlei'
p1 = text1.text_frame.add_paragraph()
p1.text = '我是段落1'
p1.add_run().text = '结束'
title_shape = slide.shapes.title
title_shape.text = 'title one'
slide.shapes.placeholders[1].text = 'title two'# 添加图形到ppt(自选图形)
shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE,Inches(2),Inches(2),Inches(5),Inches(3))
# 设置图形的填充和边框
fill = shape.fill
fill.solid()
fill.fore_color.rgb=RGBColor(255,0,0)
line = shape.line
line.color.rgb = RGBColor(55,3,5)
line.width = Pt(2)# 添加表格
table = slide.shapes.add_table(3,3,Inches(2),Inches(2),Inches(4),Inches(2)).table
table.cell(1,0).text = 'name'
table.cell(1,1).text = 'age'
table.cell(1,2).text = 'class'
table.cell(2,0).text = 'yinlei'
table.cell(2,1).text = '21'
table.cell(2,2).text = '1班'
# 合并单元格
cell = table.cell(0,0)
cell1 = table.cell(0,2)
cell.merge(cell1)
table.cell(0,0).text='student info'
#取消合并
# print(cell.is_merge_origin) # 是否合并的
# cell.split()# 插入图表
chart_data = CategoryChartData()
chart_data.categories = ['月份','一月份','二月份']
chart_data.add_series('2020', (300,400,500))
chart_data.add_series('2019', (500,300,200))
chart = slide.shapes.add_chart(XL_CHART_TYPE.LINE, Inches(2),Inches(2),Inches(6),Inches(4),chart_data).chart
chart.has_title = True
chart.chart_title.text_frame.text = '销售额'
chart.has_legend = True # 显示图例
chart.legend.position = XL_LEGEND_POSITION.RIGHT# 3. 保存ppt文件
prs.save('yinlei.pptx')

Python办公自动化之二,操作word相关推荐

  1. Python办公自动化(二)|从Excel到Word

    前言 在前几天的文章中我们讲解了如何从Word表格中提取指定数据并按照格式保存到Excel中,今天我们将再次以一位读者提出的真实需求来讲解如何使用Python从Excel中计算.整理数据并写入Word ...

  2. python在windows下操作word的方法的代码

    把写内容过程经常用的一些内容收藏起来,下边内容内容是关于python在windows下操作word的方法的内容,希望能对各位朋友有些好处. import win32com from win32com. ...

  3. python使用python-docx自动化操作word

    目录 前言 一.python-docx库简介 二.读写Word文档 2.1  创建Word文档对象 2.2  获取Word文档中的对象 2.3  将数据写入Word文档 三.修改Word文档样式 四. ...

  4. Python办公自动化之Excel转Word

    在日常工作中,Python在办公自动化领域应用非常广泛,如批量将多个Excel中的数据进行计算并生成图表,批量将多个Excel按固定格式转换成Word,或者定时生成文件并发送邮件等场景.本文主要以一个 ...

  5. python入门教程2word-python操作word入门

    1.安装pywin32 http://sourceforge.net/projects/pywin32 在files里去找适合你的python版本.截止此文,最新版本是pywin32-219快捷路径: ...

  6. Python办公自动化之 openpyxl 操作 Excel

    今天给大家分享一篇用 openpyxl 操作 Excel 的 Python 办公自动化文章.5分钟就能掌握- 各种数据需要导入Excel?多个Excel要合并?目前,Python处理Excel文件有很 ...

  7. python办公代码_[Python] 自动化办公 docx操作Word基础代码

    转载请注明:陈熹 chenx6542@foxmail.com (简书号:半为花间酒) 若公众号内转载请联系公众号:早起Python 文中的截图均为原创,转载请注明来源 安装 docx 是一个非标准库, ...

  8. python自动化办公入门-[Python] 自动化办公 docx操作Word基础代码

    转载请注明:陈熹 chenx6542@foxmail.com (简书号:半为花间酒) 若公众号内转载请联系公众号:早起Python 文中的截图均为原创,转载请注明来源 安装 docx 是一个非标准库, ...

  9. python 办公自动化-python办公自动化:Excel操作入门

    1.安装 pip install xlsxwriter or easy_install xlsxwriter or tar -zxvf xlsxwriter-*.*.*.tar.gz python s ...

最新文章

  1. 定时备份MySQL数据库
  2. 关于matlab的单精度与双精度
  3. (chap4 IP协议) CIDR协议
  4. 自用懒加载(其实效果并不是很好),自带的懒加载还好(2)(优化)
  5. Ajax表格控件实现
  6. attr 和 prop 区别
  7. coc部落冲突关联错误101解决方案
  8. 这是目前为止5G最完整的PPT
  9. 使用Ahk2Exe工具将AutoHotKey脚本打包到Windows可执行文件
  10. 支票数字大写转换器_信用卡支票数字生成器Java程序
  11. element拼音模糊搜索
  12. 悬置线高通滤波器设计
  13. python整数因式分解
  14. html上自动显示汉字拼音,今天才知道,原来html上用这个标签显示拼音
  15. 云服务器网站不显示图片,解决帝国cms图片显示不出来的问题
  16. Java去除中英文标点符号
  17. 完了!Python黄了! 80%的程序员:痛快!你怎么看?
  18. 结构静力分析与动力学分析_51CAE_新浪博客
  19. 一个事物两个方面的对比举例_对比属于修辞手法吗
  20. JVM 中一次完整的 GC 流程是什么样子的,对象如何晋升到老年代,

热门文章

  1. docker出现no matching manifest for windows/amd64 10.0.18363 in the manifest list entries错误
  2. bilibili自动挂机PHP_BilibiliHelper
  3. 集成zxing扫码解决二维码自动放大
  4. 那些年啊,那些事——一个程序员的奋斗史 ——102
  5. Python分析宋小宝的处女作《发财日记》,看看这部一亿播放量的电影
  6. css选择器类型伪类选择器(详)
  7. python 读取pdf图片_使用Python从pdf中提取图像
  8. VSCode安装ESP32开发环境ESP-IDF
  9. 【C语言】C语言三角形打印
  10. Graph disconnected: cannot obtain value for tensor Tensor