Python 进行Office开发(以Word为例)

 

要使用Python控制MS Word,您需要先安装win32com套件,这个套件可以到 http://sourceforge.net/projects/pywin32/ 找到。您需要先import win32com模块才能进行Word的控制。

 

from win32com.client import Dispatch, constants from win32com.client.gencache import EnsureDispatch EnsureDispatch('Word.Application') #makepy 导入Word类库,否则constants无法使用 msword = Dispatch('Word.Application') msword.Visible = True #是否可见 msword.DisplayAlerts = 0 doc = msword.Documents.Open(FileName = strDir + r'tbbts01e01.docx') #打开已有文件 newdoc = msword.Documents.Add() #添加新文件 newdoc.SaveAs(‘new.docx') #另存为 

 

API 参见MSDN,因为是通过COM调用的,所以APIMSDN上的一样。

http://msdn.microsoft.com/en-us/library/ms254954.aspx

 

经常使用的API: doc.Range()

 

注意: Python来开发Word速度实在是太慢,建议用C#

 

 

在使用win32com 之前,需要导入指定的类库(Makepy, 方法:

There are a couple of different ways to run makepy.

Start Pythonwin, and from the menu select Tools->Com Makepy Utility. You should see a list

of registered typelibs. Select "Microsoft Word x.y Object Library" and hit Ok.

This can also be done programatically by initiating Word with

win32com.client.gencache.EnsureDispatch('Word.Application')

 

你可能感兴趣的:(Python)