from docx import Document
document = Document()
document.save('test.docx')
这会从默认模板创建一个新文档,并将其保存到名为“test.docx”的文件中。所谓的“默认模板”其实就是一个没有内容的 Word 文件,和安装的 python-docx 包一起存放。它与 Word 文档的模板大致相同。
打开现有文档:
document = Document('existing-document-file.docx')`
可以传递打开的文件或 StringIO/BytesIO 流对象来打开或保存文档,如下所示:
f = open('foobar.docx', 'rb')
document = Document(f)
f.close()
# or
with open('foobar.docx', 'rb') as f:
source_stream = StringIO(f.read())
document = Document(source_stream)
source_stream.close()
...
target_stream = StringIO()
document.save(target_stream)