微软Office套件里都提供了编程接口来实现自动化办公,避免机械的重复工作,不过默认的语言是VBA,Python怎么实现?
抄VBA!
VBA代码能从录制的宏里看到,怎么转换成Python?抄!抄函数
首先启动软件
from win32com.client.gencache import EnsureDispatch
word = EnsureDispatch('Word.Application')
EnsureDispatch启动软件是最好的!
打开文档
student_info = r"E:\dirty_work\VBA\student_info.docx"
doc = word.Documents.Open(student_info)
抄赋值
语句两边由= 号连接,就是给对象的属性赋值。
Application.Width = 400 'VBA中设置Word窗口的宽度
Python里照做
word.Width = 400
抄函数
VBA中函数有三种调用形式
Selection.Find.Execute
Selection.PasteAndFormat (wdFormatPlainText)
Selection.PasteSpecial Link:=False, DataType:=14, Placement:=wdInLine, _
DisplayAsIcon:=False
抄参数
直接使用对应的Python对象就可以,类型转换会自动进行!
抄常量
Word里wd开头的,Excel里xl开头的,PPT里pp开头的基本都是常量,Python里这样做:
from win32com.client import constants
constants.wdFormatPlainText
所以
word.Selection.Find.Execute()
word.Selection.PasteAndFormat(constants.wdFormatPlainText)
word.Selection.PasteSpecial(Link=False,
DataType=14,
Placement=constants.wdInline,
DisplayAsIcon=False
)
抄with
with只是一种简写,with里的点相当于直接写到with后面的那个对象的。
'将文档中的{{phone}}替换为 138 8888 8888
With Selection.Find
.Text = "{{phone}}"
.Replacement.Text = "138 8888 8888"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
等价于
Selection.Find.Text = "{{phone}}"
Selection.Find.Replacement.Text = "138 8888 8888"
Selection.Find.Forward = True
Selection.Find.Wrap = wdFindContinue
Selection.Find.Format = False
Selection.Find.MatchCase = False
Selection.Find.MatchWholeWord = False
Selection.Find.MatchByte = True
Selection.Find.MatchWildcards = False
Selection.Find.MatchSoundsLike = False
Selection.Find.MatchAllWordForms = False
Selection.Find.Execute
加速
写好程序后想要速度,禁止屏幕更新就成,
word.ScreenUpdating = False
记得在程序退出之前设置:
word.ScreenUpdating = True
异常处理
默认的异常信息并不友好,试一试这个:
import pythoncom
try:
doing something
except pythoncom.com_error as _error:
if _error.excepinfo is None:
excepinfo = [None]*6
else:
excepinfo = _error.excepinfo
hresult_readable = u"""
hresult状态码:{0}
hresult状态码信息:{1}"""
detail_readable = u"""
错误码: {0}
错误源: {1}
错误信息:{2}
帮助文档: {3}
帮助ID: {4}
错误码: {5}
"""
args_readable = u"""参数错误,参数所在位置:{0}"""
print hresult_readable.format(_error.hresult, _error.strerror.decode('gbk'))
print detail_readable.format(*excepinfo)
if _error.argerror > 0:
print args_readable.format(_error.argerror)
其他没讲到的,就抄文档吧!
Github:Office开发文档+快速开发模板