为了账号安全,请及时绑定邮箱和手机立即绑定

【九月打卡】第9天 Python办公自动化

标签:
Python

课程名称Python办公自动化

课程章节:第5章 玩转Word自动化

课程讲师: 离岛


课程内容

Word样式处理表格样式、文字样式

https://img1.sycdn.imooc.com//6321e29f00010d0409120493.jpg

样式的是可以各个元素都可以设置,这样可以形成同一个的风格,分为两类形式属性和格式属性

from docx.enum.style import WD_STYLE_TYPE

#添加样式
style=document.styles.add_style('textstyle',WD_STYLE_TYPE.PARAGRAPH)    
print(style.style_id)    
print(style.name)    
style.font.size=Pt(5)#样式
#使用
p1 = document.add_paragraph(
'慕课网是垂直的互联网IT技能免费学习网站。以独家视频教程、在线编程工具、学习计划、问答社区为核心特色。在这里,你可以找到最好的互联网技术牛人,也可以通过免费的在线公开视频课程学习国内领先的互联网IT技术',style='textstyle')    
p1.insert_paragraph_before('!!在段落前插入一个新的段落')p1 = document.add_paragraph(


#表格样式的设置, 其中参数的可以从下面的官网进行查询
table = document.add_table(rows=1, cols=3,style='Medium List 2')

http://python-docx.readthedocs.io

document.styles['textstyle'].delete()#删除样式

Word转PDF文件, 我们需要用到pywin32模块几乎包含win的API。

安装 :pip install  pywin32

导入 from win32com.client import constants

其中 ExportAsFixedFormaopenpyxlt可以参考如下的说明

https://docs.microsoft.com/zh-cn/office/vba/api/Excel.Workbook.ExportAsFixedFormat

from win32com.client import constants,gencache
import os

def createpdf(wordPath,pdfPath):
    word=gencache.EnsureDispatch('Word.Application')
    doc=word.Documents.Open(wordPath,ReadOnly=1)
    #转换方法
    doc.ExportAsFixedFormaopenpyxlt(pdfPath,constants.wdExportFormatPDF)
    # word.Quit()

进行多个文件的转换

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'    
    print(pdfpath)    
    createpdf(filepath,pdfpath)

课程收获

本章节主要的学习内容为样式的修改和word转pdf,文件的转换离不开win32提供的系统接口,具体哪些接口需要参考官网的说明






点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消