与文档有关的对象有Document对象和Documents对象。Document对象表示文档,Documents对象为集合,对所有Document对象进行存储和管理。[大谦Excel,dqexcel点com]
使用Documents对象的Add方法创建新文档。下面导入win32com包,创建Word应用,设置它可见,然后使用Documents对象的Add方法新建一个空白文档。
>>> import win32com.client as win32
>>> app=win32.gencache.EnsureDispatch('word.application')
>>> app.Visible=True
>>> doc=app.Documents.Add(Visible=True)
下面新建文档时指定模板路径和名称给Template参数,则新建的文档使用该模板。
>>> doc=app.Documents.Add(Template="C:\Program Files(x86)\Microsoft Office\Templates\
2052\StudentReport.dotx",Visible=True)
新建的Word文档如图2-1所示。
图2-1 新建文档使用指定模板
使用Documents对象的Open方法打开已经存在的文档。下面的代码以只读方式打开D盘下的test.docx文件。
>>> doc=app.Documents.Open(FileName="D:\\test.docx", ReadOnly=True)
保存文档时,根据文档的情况使用不同的方法进行操作。对于打开的已经保存过的文档,使用Document对象的Save方法进行保存;对于新建文档,使用Document对象的Save2方法进行保存。
保存文档时常常进行一个判断,当保存过的文档打开后,如果没有被修改,则不必进行保存;被修改过了,进行保存。使用Document对象的Saved属性,可以判断该文档打开后是否进行了修改。如果值为True,说明文档没有被修改,值为False时表示文档被修改了。于是有类似下面的编码方法。
>>> if app.ActiveDocument.Saved==False:
app.ActiveDocument.Save()
对于新建的文档,保存时使用Document对象的SaveAs2方法。下面新建一个文档,使用Document对象的SaveAs2方法将它保存为Docx格式的文件。
>>> import win32com.client as win32
>>> app=win32.gencache.EnsureDispatch('word.application')
>>> app.Visible=True
>>> doc=app.Documents.Add(Visible=True)
>>> doc.SaveAs2('D:\\test2.docx')
将文档另存为PDF文件test.pdf。
>>> doc.SaveAs2(FileName="D:\\test.pdf",FileFormat= constants.wdFormatPDF)
将文档另存为文本文件test.txt。
>>> doc.SaveAs2(FileName="D:\\test.txt",FileFormat= constants.wdFormatText)
每一个新建的或新打开的文档,都会作为Document对象添加到Documents集合中,并且得到一个索引号。第1个添加进集合的索引号为1,第2个的为2,以此类推。当需要对集合中的某个文档进行处理时,可以利用这个索引号找到它,找到它这个操作称为引用。
下面两行代码分别新建一个文档和打开一个已有文件。
>>> doc=app.Documents.Add(Visible=True)
>>> doc2=app.Documents.Open('D:\\test.docx')
这两个文档都会自动添加到Documents集合中。查看Documents集合中的文档个数。
>>> app.Documents.Count
2
利用索引号查看集合中两个文档的文件名。
>>> app.Documents(1).Name
'test.docx'
>>> app.Documents(2).Name
'文档2'
除了使用索引号引用文档,还可以使用文档的名称进行引用,例如:
>>> app.Documents('文档2').Name
'文档2'
使用Document对象的Close方法关闭文档。下面关闭集合中的第1个文档。
>>> app.Documents(1).Close()
查看集合中的文档个数。
>>> app.Documents.Count
1
现在集合中只有1个文档了。