1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 import win32com.client 4 import os 5 #-------------------------------------------------------------------------- 6 class easyWord: 7 ''' 8 Some convenience methods for Excel documents accessed 9 through COM.一些方便的方法為Excel文檔接入通過COM 10 ''' 11 def __init__(self,visible=False): 12 self.wdApp = win32com.client.Dispatch('Word.Application') 13 self.wdApp.Visible = visible 14 15 16 def new(self,filename=None): 17 ''' 18 Create a new Word document. If 'filename' specified, 19 use the file as a template.創建一個新的word文件, 20 ''' 21 if filename: 22 return self.wdApp.Documents.Add(filename) 23 else: 24 return self.wdApp.Documents.Add() 25 26 27 def open(self,filename): 28 ''' 29 Open an existing Word document for editing. 30 打開一個已經存在的word進行編輯 31 ''' 32 return self.wdApp.Documents.Open(filename) 33 def visible(self,visible=True): 34 self.wdApp.Visible = visible 35 36 37 def find(self,text,MatchWildcards=False): 38 ''' 39 Find the string 40 查找字符串 41 ''' 42 find = self.wdApp.Selection.Find 43 find.ClearFormatting() 44 find.Execute(text, False, False, MatchWildcards, False, False, True, 0) 45 return self.wdApp.Selection.Text 46 def replaceAll(self,oldStr,newStr): 47 ''' 48 Find the oldStr and replace with the newStr. 49 替換所有字符串 50 ''' 51 find = self.wdApp.Selection.Find 52 find.ClearFormatting() 53 find.Replacement.ClearFormatting() 54 find.Execute(oldStr, False, False, False, False, False, True, 1, True, newStr, 2) 55 def updateToc(self): 56 for tocitem in self.wdApp.ActiveDocument.TablesOfContents: 57 tocitem.Update() 58 def save(self): 59 ''' 60 Save the active document 61 ''' 62 self.wdApp.ActiveDocument.Save() 63 def saveAs(self,filename,delete_existing=True): 64 ''' 65 Save the active document as a different filename. 66 If 'delete_existing' is specified and the file already 67 exists, it will be deleted before saving. 68 ''' 69 if delete_existing and os.path.exists(filename): 70 os.remove(filename) 71 self.wdApp.ActiveDocument.SaveAs(FileName = filename) 72 def close(self): 73 ''' 74 Close the active workbook. 75 ''' 76 self.wdApp.ActiveDocument.Close() 77 def quit(self): 78 ''' 79 Quit Word 80 ''' 81 return self.wdApp.Quit()