文書の作成または読み込み
Aspose.Wordsを使用して実行するほとんどのタスクには、文書の読み込みが含まれます。 Document
クラスは、メモリにロードされたドキュメントを表します。 ドキュメントには複数のオーバーロードされたコンストラクターがあり、空のドキュメントを作成したり、ファイルやストリームからロードしたりできます。 文書はAspose.Wordsでサポートされている任意の読み込み形式で読み込むことができます。 サポートされているすべてのロード形式の一覧については、LoadFormat列挙体を参照してください。
新しい文書{#create-a-new-document}を作成する
パラメータなしでDocumentコンストラクタを呼び出して、新しい空の文書を作成します。 プログラムでドキュメントを生成する場合、最も簡単な方法はDocumentBuilderクラスを使用してドキュメントの内容を追加することです。
次のコード例は、document builderを使用してドキュメントを作成する方法を示しています:
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); |
デフォルト値に注意してください:
- 空白の文書には、デフォルトのパラメータ、空の段落、いくつかの文書スタイルを持つセクションが含まれています。 実際には、この文書はMicrosoft Wordに"新しい文書"を作成した結果と同じです。
- 原稿用紙サイズはPaperSizeです。Letter.
文書を読み込む
既存のドキュメントを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.
ストリーム{#load-from-a-stream}から読み込む
ストリームからドキュメントを開くには、ドキュメントを含むstreamオブジェクトをドキュメントコンストラクタに渡すだけです。
次のコード例は、ストリームからドキュメントを開く方法を示しています:
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(); |