创建或加载文档

几乎您想要使用 Aspose.Words 执行的任何任务都涉及加载文档。 Document 类表示加载到内存中的文档。该文档有几个重载的构造函数,允许您创建空白文档或从文件或流加载它。文档可以以 Aspose.Words 支持的任何加载格式加载。有关所有支持的加载格式的列表,请参阅 LoadFormat 枚举。

创建新文档

我们将调用不带参数的 Document 构造函数来创建一个新的空白文档。如果要以编程方式生成文档,最简单的方法是使用 DocumentBuilder 类添加文档内容。

以下代码示例展示了如何使用文档生成器创建文档:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
// Use a document builder to add content to the document.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Hello World!");
doc.Save(ArtifactsDir + "AddContentUsingDocumentBuilder.CreateNewDocument.docx");
view raw create-docx.cs hosted with ❤ by GitHub

加载文档

要加载任何 LoadFormat 格式的现有文档,请将文件名或流传递到文档构造函数之一。加载文档的格式由其扩展名自动确定。

从文件 {#load-from-a-file} 加载

将文件名作为字符串传递给 Document 构造函数以从文件打开现有文档。

以下代码示例演示如何从文件打开文档:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(MyDir + "Document.docx");
view raw load-docx.cs hosted with ❤ by GitHub

您可以从Aspose.Words GitHub下载本示例的模板文件。

从流 {#load-from-a-stream} 加载

要从流中打开文档,只需将包含文档的流对象传递到 Document 构造函数即可。

以下代码示例演示如何从流中打开文档:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Read only access is enough for Aspose.Words to load a document.
Stream stream = File.OpenRead(MyDir + "Document.docx");
Document doc = new Document(stream);
// You can close the stream now, it is no longer needed because the document is in memory.
stream.Close();