环境:Python3.6
本文主要是通过win32com操作word,对word中进行常用的操作。本文以替换为例,讲解一下如何使用Python在word中使用“通配符模式”(类似于正则表达式)替换文本内容。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import win32com
from win32com.client import Dispatch
# 处理Word文档的类
class RemoteWord:
def __init__(self, filename=None):
self.xlApp = win32com.client.Dispatch('Word.Application') # 此处使用的是Dispatch,原文中使用的DispatchEx会报错
self.xlApp.Visible = 0 # 后台运行,不显示
self.xlApp.DisplayAlerts = 0 #不警告
if filename:
self.filename = filename
if os.path.exists(self.filename):
self.doc = self.xlApp.Documents.Open(filename)
else:
self.doc = self.xlApp.Documents.Add() # 创建新的文档
self.doc.SaveAs(filename)
else:
self.doc = self.xlApp.Documents.Add()
self.file