创建或加载文档

几乎任何要使用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-C
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_LoadingAndSaving();
// Initialize a Document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Use a document builder to add content to the document.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"Hello World!");
System::String outputPath = outputDataDir + u"CreateDocument.docx";
// Save the document to disk.
doc->Save(outputPath);

加载文档

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

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

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

下面的代码示例演示如何从文件中打开文档:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
System::String outputDataDir = GetOutputDataDir_LoadingAndSaving();
// Load the document from the absolute path on disk.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.docx");

您可以从以下位置下载此示例的模板文件 Aspose.Words GitHub.

从流加载

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

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

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_LoadingAndSaving();
System::String outputDataDir = GetOutputDataDir_LoadingAndSaving();
// Open the stream. Read only access is enough for Aspose.Words to load a document.
System::SharedPtr<System::IO::Stream> stream = System::IO::File::OpenRead(inputDataDir + u"Document.docx");
// Load the entire document into memory.
System::SharedPtr<Document> doc = System::MakeObject<Document>(stream);
// You can close the stream now, it is no longer needed because the document is in memory.
stream->Close();