Word.Document class

Document オブジェクトは、最上位レベルのオブジェクトです。 ドキュメント オブジェクトには、1 つ以上のセクション、コンテンツ コントロール、ドキュメントの内容を含む本文が含まれています。

Extends

注釈

[ API セット: WordApi 1.1 ]

プロパティ

body

メイン ドキュメントの body オブジェクトを取得します。 本文は、ヘッダー、フッター、脚注、テキスト ボックスなどを除外するテキストです。

changeTrackingMode

ChangeTracking モードを指定します。

contentControls

ドキュメント内のコンテンツ コントロール オブジェクトのコレクションを取得します。 これには、ドキュメントの本文、ヘッダー、フッター、テキスト ボックスなどのコンテンツ コントロールが含まれます。

context

オブジェクトに関連付けられている要求コンテキスト。 これにより、アドインのプロセスが Office ホスト アプリケーションのプロセスに接続されます。

customXmlParts

ドキュメント内のカスタム XML パーツを取得します。

properties

ドキュメントのプロパティを取得します。

saved

ドキュメント内の変更が保存されているかどうかを示します。 値 true は、ドキュメントが保存されてから変更されていないことを示します。

sections

ドキュメント内のセクション オブジェクトのコレクションを取得します。

settings

ドキュメント内のアドインの設定を取得します。

メソッド

addStyle(name, type)

名前と種類によってスタイルをドキュメントに追加します。

addStyle(name, typeString)

名前と種類によってスタイルをドキュメントに追加します。

close(closeBehavior)

現在のドキュメントを閉じます。

close(closeBehaviorString)

現在のドキュメントを閉じます。

compare(filePath, documentCompareOptions)

指定された文書と別の文書を比較して、変更箇所を示す変更履歴を表示します。

deleteBookmark(name)

ブックマークが存在する場合は、ドキュメントから削除します。

getAnnotationById(id)

ID で注釈を取得します。 注釈が ItemNotFound 見つからない場合にエラーをスローします。

getBookmarkRange(name)

ブックマークの範囲を取得します。 ブックマークが ItemNotFound 存在しない場合は、エラーをスローします。

getBookmarkRangeOrNullObject(name)

ブックマークの範囲を取得します。 ブックマークが存在しない場合、このメソッドは プロパティが に設定されたオブジェクトをisNullObjecttrue返します。 詳細については、「 *OrNullObject メソッドとプロパティ」を参照してください。

getContentControls(options)

ドキュメントで現在サポートされているコンテンツ コントロールを取得します。

getEndnoteBody()

文書の文末脚注を 1 つの本文で取得します。

getFootnoteBody()

文書の脚注を 1 つの本文で取得します。

getParagraphByUniqueLocalId(id)

一意のローカル ID で段落を取得します。 コレクションが空の ItemNotFound 場合にエラーをスローします。

getSelection()

ドキュメントの現在の選択範囲を取得します。 複数の選択はサポートされていません。

getStyles()

ドキュメントのスタイル セット全体を表す StyleCollection オブジェクトを取得します。

importStylesFromJson(stylesJson)

JSON 形式の文字列からスタイルをインポートします。

insertFileFromBase64(base64File, insertLocation, insertFileOptions)

追加のプロパティを使用して、特定の場所にあるターゲット ドキュメントにドキュメントを挿入します。 ヘッダー、フッター、透かし、およびその他のセクション プロパティは、既定でコピーされます。

load(options)

オブジェクトの指定されたプロパティを読み込むコマンドを待ち行列に入れます。 プロパティを読み取る前に、context.sync() を呼び出す必要があります。

load(propertyNames)

オブジェクトの指定されたプロパティを読み込むコマンドを待ち行列に入れます。 プロパティを読み取る前に、context.sync() を呼び出す必要があります。

load(propertyNamesAndPaths)

オブジェクトの指定されたプロパティを読み込むコマンドを待ち行列に入れます。 プロパティを読み取る前に、context.sync() を呼び出す必要があります。

save(saveBehavior, fileName)

ドキュメントを保存します。

save(saveBehaviorString, fileName)

ドキュメントを保存します。

search(searchText, searchOptions)

指定した検索オプションを使用して、ドキュメント全体のスコープで検索を実行します。 検索結果は、範囲オブジェクトのコレクションです。

set(properties, options)

オブジェクトの複数のプロパティを同時に設定します。 適切なプロパティを持つプレーン オブジェクトまたは同じ型の別の API オブジェクトを渡すことができます。

set(properties)

既存の読み込まれたオブジェクトに基づいて、オブジェクトに複数のプロパティを同時に設定します。

toJSON()

API オブジェクトが に渡されたときにより便利な出力を提供するために、JavaScript toJSON() メソッドを JSON.stringify()オーバーライドします。 (JSON.stringifyさらに、渡される オブジェクトの メソッドを呼び出toJSONします)。一方、元のWord。Document オブジェクトは API オブジェクトです。メソッドは、元のtoJSONオブジェクトから読み込まれた子プロパティの浅いコピーを含むプレーンな JavaScript オブジェクト (としてWord.Interfaces.DocumentData型指定) を返します。

track()

ドキュメントの環境変更に基づいて自動的に調整する目的でオブジェクトを追跡します。 この呼び出しは、context.trackedObjects.add(thisObject)の短縮形です。 このオブジェクトを呼び出しで .sync 使用していて、".run" バッチのシーケンシャル実行の外部で使用していて、プロパティを設定するとき、またはオブジェクトのメソッドを呼び出すときに "InvalidObjectPath" エラーが発生する場合は、オブジェクトが最初に作成されたときに追跡対象のオブジェクト コレクションにオブジェクトを追加する必要があります。 このオブジェクトがコレクションの一部である場合は、親コレクションも追跡する必要があります。

untrack()

前に追跡されていた場合、このオブジェクトに関連付けられているメモリを解放します。 この呼び出しは、context.trackedObjects.remove(thisObject)の短縮形です。 追跡対象オブジェクトが多いとホスト アプリケーションの動作が遅くなります。追加したオブジェクトが不要になったら、必ずそれを解放してください。 メモリ解放が有効になる前に を呼び出す context.sync() 必要があります。

イベント

onAnnotationClicked

ユーザーが注釈をクリック (または Alt + Down を使用して選択) したときに発生します。

onAnnotationHovered

ユーザーが注釈の上にカーソルを合わせると発生します。

onAnnotationInserted

ユーザーが 1 つ以上の注釈を追加するときに発生します。

onAnnotationPopupAction

ユーザーが注釈ポップアップ メニューでアクションを実行したときに発生します。

onAnnotationRemoved

ユーザーが 1 つ以上の注釈を削除するときに発生します。

onContentControlAdded

コンテンツ コントロールが追加されたときに発生します。 ハンドラーで context.sync() を実行して、新しいコンテンツ コントロールのプロパティを取得します。

onParagraphAdded

ユーザーが新しい段落を追加するときに発生します。

onParagraphChanged

ユーザーが段落を変更したときに発生します。

onParagraphDeleted

ユーザーが段落を削除したときに発生します。

プロパティの詳細

body

メイン ドキュメントの body オブジェクトを取得します。 本文は、ヘッダー、フッター、脚注、テキスト ボックスなどを除外するテキストです。

readonly body: Word.Body;

プロパティ値

注釈

[ API セット: WordApi 1.1 ]

changeTrackingMode

ChangeTracking モードを指定します。

changeTrackingMode: Word.ChangeTrackingMode | "Off" | "TrackAll" | "TrackMineOnly";

プロパティ値

Word.ChangeTrackingMode | "Off" | "TrackAll" | "TrackMineOnly"

注釈

[ API セット: WordApi 1.4 ]

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-change-tracking.yaml

// Gets the current change tracking mode.
await Word.run(async (context) => {
  const document = context.document;
  document.load("changeTrackingMode");
  await context.sync();

  if (document.changeTrackingMode === Word.ChangeTrackingMode.trackMineOnly) {
    console.log("Only my changes are being tracked.");
  } else if (document.changeTrackingMode === Word.ChangeTrackingMode.trackAll) {
    console.log("Everyone's changes are being tracked.");
  } else {
    console.log("No changes are being tracked.");
  }
});

contentControls

ドキュメント内のコンテンツ コントロール オブジェクトのコレクションを取得します。 これには、ドキュメントの本文、ヘッダー、フッター、テキスト ボックスなどのコンテンツ コントロールが含まれます。

readonly contentControls: Word.ContentControlCollection;

プロパティ値

注釈

[ API セット: WordApi 1.1 ]

context

オブジェクトに関連付けられている要求コンテキスト。 これにより、アドインのプロセスが Office ホスト アプリケーションのプロセスに接続されます。

context: RequestContext;

プロパティ値

customXmlParts

ドキュメント内のカスタム XML パーツを取得します。

readonly customXmlParts: Word.CustomXmlPartCollection;

プロパティ値

注釈

[ API セット: WordApi 1.4 ]

properties

ドキュメントのプロパティを取得します。

readonly properties: Word.DocumentProperties;

プロパティ値

注釈

[ API セット: WordApi 1.3 ]

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/30-properties/get-built-in-properties.yaml

await Word.run(async (context) => {
    const builtInProperties = context.document.properties;
    builtInProperties.load("*"); // Let's get all!

    await context.sync();
    console.log(JSON.stringify(builtInProperties, null, 4));
});

saved

ドキュメント内の変更が保存されているかどうかを示します。 値 true は、ドキュメントが保存されてから変更されていないことを示します。

readonly saved: boolean;

プロパティ値

boolean

注釈

[ API セット: WordApi 1.1 ]

sections

ドキュメント内のセクション オブジェクトのコレクションを取得します。

readonly sections: Word.SectionCollection;

プロパティ値

注釈

[ API セット: WordApi 1.1 ]

settings

ドキュメント内のアドインの設定を取得します。

readonly settings: Word.SettingCollection;

プロパティ値

注釈

[ API セット: WordApi 1.4 ]

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-settings.yaml

// Gets all custom settings this add-in set on this document.
await Word.run(async (context) => {
  const settings = context.document.settings;
  settings.load("items");
  await context.sync();

  if (settings.items.length == 0) {
    console.log("There are no settings");
  } else {
    console.log("All settings:");
    for (let i = 0; i < settings.items.length; i++) {
      console.log(settings.items[i]);
    }
  }
});

メソッドの詳細

addStyle(name, type)

名前と種類によってスタイルをドキュメントに追加します。

addStyle(name: string, type: Word.StyleType): Word.Style;

パラメーター

name

string

必須です。 スタイル名を表す文字列。

type
Word.StyleType

必須です。 文字、リスト、段落、またはテーブルを含むスタイルの種類。

戻り値

注釈

[ API セット: WordApi 1.5 ]

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-styles.yaml

// Adds a new style.
await Word.run(async (context) => {
  const newStyleName = $("#new-style-name").val() as string;
  if (newStyleName == "") {
    console.warn("Enter a style name to add.");
    return;
  }

  const style = context.document.getStyles().getByNameOrNullObject(newStyleName);
  style.load();
  await context.sync();

  if (!style.isNullObject) {
    console.warn(
      `There's an existing style with the same name '${newStyleName}'! Please provide another style name.`
    );
    return;
  }

  const newStyleType = ($("#new-style-type").val() as unknown) as Word.StyleType;
  context.document.addStyle(newStyleName, newStyleType);
  await context.sync();
  
  console.log(newStyleName + " has been added to the style list.");
});

addStyle(name, typeString)

名前と種類によってスタイルをドキュメントに追加します。

addStyle(name: string, typeString: "Character" | "List" | "Paragraph" | "Table"): Word.Style;

パラメーター

name

string

必須です。 スタイル名を表す文字列。

typeString

"Character" | "List" | "Paragraph" | "Table"

必須です。 文字、リスト、段落、またはテーブルを含むスタイルの種類。

戻り値

注釈

[ API セット: WordApi 1.5 ]

close(closeBehavior)

現在のドキュメントを閉じます。

close(closeBehavior?: Word.CloseBehavior): void;

パラメーター

closeBehavior
Word.CloseBehavior

オプション。 閉じる動作は、'Save' または 'SkipSave' である必要があります。 既定値は 'Save' です。

戻り値

void

注釈

[ API セット: WordApi 1.5 ]

close(closeBehaviorString)

現在のドキュメントを閉じます。

close(closeBehaviorString?: "Save" | "SkipSave"): void;

パラメーター

closeBehaviorString

"Save" | "SkipSave"

オプション。 閉じる動作は、'Save' または 'SkipSave' である必要があります。 既定値は 'Save' です。

戻り値

void

注釈

[ API セット: WordApi 1.5 ]

compare(filePath, documentCompareOptions)

注意

この API は開発者向けにプレビューとして提供されており、寄せられたフィードバックにもとづいて変更される場合があります。 この API は運用環境で使用しないでください。

指定された文書と別の文書を比較して、変更箇所を示す変更履歴を表示します。

compare(filePath: string, documentCompareOptions?: Word.DocumentCompareOptions): void;

パラメーター

filePath

string

必須です。 指定したドキュメントを比較するドキュメントのパス。

documentCompareOptions
Word.DocumentCompareOptions

オプション。 ドキュメントの比較の動作を指定する追加のオプション。

戻り値

void

注釈

[ API セット: WordApi BETA (プレビューのみ) ]

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/99-preview-apis/compare-documents.yaml

// Compares the current document with a specified external document.
await Word.run(async (context) => {
  // Absolute path of an online or local document.
  const filePath = $("#filePath")
    .val()
    .toString();
  // Options that configure the compare operation.
  const options = {
    compareTarget: Word.CompareTarget.compareTargetCurrent,
    detectFormatChanges: false
    // Other options you choose...
    };
  context.document.compare(filePath, options);

  await context.sync();

  console.log("Differences shown in the current document.");
});

deleteBookmark(name)

ブックマークが存在する場合は、ドキュメントから削除します。

deleteBookmark(name: string): void;

パラメーター

name

string

必須です。 大文字と小文字を区別しないブックマーク名。

戻り値

void

注釈

[ API セット: WordApi 1.4 ]

getAnnotationById(id)

ID で注釈を取得します。 注釈が ItemNotFound 見つからない場合にエラーをスローします。

getAnnotationById(id: string): Word.Annotation;

パラメーター

id

string

取得する注釈の ID。

戻り値

注釈

[ API セット: WordApi 1.7 ]

getBookmarkRange(name)

ブックマークの範囲を取得します。 ブックマークが ItemNotFound 存在しない場合は、エラーをスローします。

getBookmarkRange(name: string): Word.Range;

パラメーター

name

string

必須です。 大文字と小文字を区別しないブックマーク名。

戻り値

注釈

[ API セット: WordApi 1.4 ]

getBookmarkRangeOrNullObject(name)

ブックマークの範囲を取得します。 ブックマークが存在しない場合、このメソッドは プロパティが に設定されたオブジェクトをisNullObjecttrue返します。 詳細については、「 *OrNullObject メソッドとプロパティ」を参照してください。

getBookmarkRangeOrNullObject(name: string): Word.Range;

パラメーター

name

string

必須です。 大文字と小文字を区別しないブックマーク名。

戻り値

注釈

[ API セット: WordApi 1.4 ]

getContentControls(options)

ドキュメントで現在サポートされているコンテンツ コントロールを取得します。

getContentControls(options?: Word.ContentControlOptions): Word.ContentControlCollection;

パラメーター

options
Word.ContentControlOptions

省略可能です。 返されるコンテンツ コントロールを定義するオプション。

戻り値

注釈

[ API セット: WordApi 1.5 ]

重要: options パラメーターに特定の型が指定されている場合、サポートされている型のコンテンツ コントロールのみが返されます。 ジェネリック Wordのメソッドを使用すると、例外がスローされることに注意してください特定の種類に関連しない ContentControl。 時間によっては、追加の種類のコンテンツ コントロールがサポートされる場合があります。 そのため、アドインは特定の種類のコンテンツ コントロールを要求して処理する必要があります。

getEndnoteBody()

文書の文末脚注を 1 つの本文で取得します。

getEndnoteBody(): Word.Body;

戻り値

注釈

[ API セット: WordApi 1.5 ]

getFootnoteBody()

文書の脚注を 1 つの本文で取得します。

getFootnoteBody(): Word.Body;

戻り値

注釈

[ API セット: WordApi 1.5 ]

getParagraphByUniqueLocalId(id)

一意のローカル ID で段落を取得します。 コレクションが空の ItemNotFound 場合にエラーをスローします。

getParagraphByUniqueLocalId(id: string): Word.Paragraph;

パラメーター

id

string

必須です。 標準の 8-4-4-4-12 GUID 形式の一意のローカル ID(中かっこなし)。 ID は、セッションと共同編集者によって異なる点に注意してください。

戻り値

注釈

[ API セット: WordApi 1.6 ]

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/onadded-event.yaml

await Word.run(async (context) => {
  const paragraphId = $("#paragraph-id").val() as string;
  const paragraph = context.document.getParagraphByUniqueLocalId(paragraphId);
  paragraph.load();
  await paragraph.context.sync();

  console.log(paragraph);
});

getSelection()

ドキュメントの現在の選択範囲を取得します。 複数の選択はサポートされていません。

getSelection(): Word.Range;

戻り値

注釈

[ API セット: WordApi 1.1 ]

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    const textSample = 'This is an example of the insert text method. This is a method ' + 
        'which allows users to insert text into a selection. It can insert text into a ' +
        'relative location or it can overwrite the current selection. Since the ' +
        'getSelection method returns a range object, look up the range object documentation ' +
        'for everything you can do with a selection.';
    
    // Create a range proxy object for the current selection.
    const range = context.document.getSelection();
    
    // Queue a command to insert text at the end of the selection.
    range.insertText(textSample, Word.InsertLocation.end);
    
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Inserted the text at the end of the selection.');
});  

getStyles()

ドキュメントのスタイル セット全体を表す StyleCollection オブジェクトを取得します。

getStyles(): Word.StyleCollection;

戻り値

注釈

[ API セット: WordApi 1.5 ]

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-styles.yaml

// Gets the number of styles.
await Word.run(async (context) => {
  const styles = context.document.getStyles();
  const count = styles.getCount();
  await context.sync();

  console.log(`Number of styles: ${count.value}`);
});

importStylesFromJson(stylesJson)

JSON 形式の文字列からスタイルをインポートします。

importStylesFromJson(stylesJson: string): OfficeExtension.ClientResult<string[]>;

パラメーター

stylesJson

string

必須です。 スタイルを表す JSON 形式の文字列。

戻り値

注釈

[ API セット: WordApi 1.6 ]

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/99-preview-apis/manage-custom-style.yaml

// Imports styles from JSON.
await Word.run(async (context) => {
  const str =
    '{"styles":[{"baseStyle":"Default Paragraph Font","builtIn":false,"inUse":true,"linked":false,"nameLocal":"NewCharStyle","priority":2,"quickStyle":true,"type":"Character","unhideWhenUsed":false,"visibility":false,"paragraphFormat":null,"font":{"name":"DengXian Light","size":16.0,"bold":true,"italic":false,"color":"#F1A983","underline":"None","subscript":false,"superscript":true,"strikeThrough":true,"doubleStrikeThrough":false,"highlightColor":null,"hidden":false},"shading":{"backgroundPatternColor":"#FF0000"}},{"baseStyle":"Normal","builtIn":false,"inUse":true,"linked":false,"nextParagraphStyle":"NewParaStyle","nameLocal":"NewParaStyle","priority":1,"quickStyle":true,"type":"Paragraph","unhideWhenUsed":false,"visibility":false,"paragraphFormat":{"alignment":"Centered","firstLineIndent":0.0,"keepTogether":false,"keepWithNext":false,"leftIndent":72.0,"lineSpacing":18.0,"lineUnitAfter":0.0,"lineUnitBefore":0.0,"mirrorIndents":false,"outlineLevel":"OutlineLevelBodyText","rightIndent":72.0,"spaceAfter":30.0,"spaceBefore":30.0,"widowControl":true},"font":{"name":"DengXian","size":14.0,"bold":true,"italic":true,"color":"#8DD873","underline":"Single","subscript":false,"superscript":false,"strikeThrough":false,"doubleStrikeThrough":true,"highlightColor":null,"hidden":false},"shading":{"backgroundPatternColor":"#00FF00"}},{"baseStyle":"Table Normal","builtIn":false,"inUse":true,"linked":false,"nextParagraphStyle":"NewTableStyle","nameLocal":"NewTableStyle","priority":100,"type":"Table","unhideWhenUsed":false,"visibility":false,"paragraphFormat":{"alignment":"Left","firstLineIndent":0.0,"keepTogether":false,"keepWithNext":false,"leftIndent":0.0,"lineSpacing":12.0,"lineUnitAfter":0.0,"lineUnitBefore":0.0,"mirrorIndents":false,"outlineLevel":"OutlineLevelBodyText","rightIndent":0.0,"spaceAfter":0.0,"spaceBefore":0.0,"widowControl":true},"font":{"name":"DengXian","size":20.0,"bold":false,"italic":true,"color":"#D86DCB","underline":"None","subscript":false,"superscript":false,"strikeThrough":false,"doubleStrikeThrough":false,"highlightColor":null,"hidden":false},"tableStyle":{"allowBreakAcrossPage":true,"alignment":"Left","bottomCellMargin":0.0,"leftCellMargin":0.08,"rightCellMargin":0.08,"topCellMargin":0.0,"cellSpacing":0.0},"shading":{"backgroundPatternColor":"#60CAF3"}}]}';
  const styles = context.document.importStylesFromJson(str);
  await context.sync();
  console.log("Styles imported from JSON:");
  console.log(styles);
});

insertFileFromBase64(base64File, insertLocation, insertFileOptions)

追加のプロパティを使用して、特定の場所にあるターゲット ドキュメントにドキュメントを挿入します。 ヘッダー、フッター、透かし、およびその他のセクション プロパティは、既定でコピーされます。

insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End", insertFileOptions?: Word.InsertFileOptions): Word.SectionCollection;

パラメーター

base64File

string

必須です。 .docx ファイルの Base64 でエンコードされたコンテンツ。

insertLocation

replace | start | end | "Replace" | "Start" | "End"

必須です。 値は、'Replace'、'Start'、または 'End' である必要があります。

insertFileOptions
Word.InsertFileOptions

オプション。 コピー先ドキュメントにインポートする必要がある追加のプロパティ。

戻り値

注釈

[ API セット: WordApi 1.5 ]

注: 挿入するドキュメントに ActiveX コントロールが含まれている場合 (フォーム フィールドの可能性があります)、挿入はサポートされません。 このようなフォーム フィールドを、シナリオに適したコンテンツ コントロールまたはその他のオプションに置き換えることを検討してください。

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/insert-external-document.yaml

// Inserts content (applying selected settings) from another document passed in as a Base64-encoded string.
await Word.run(async (context) => {
  // Use the Base64-encoded string representation of the selected .docx file.
  context.document.insertFileFromBase64(externalDocument, "Replace", {
    importTheme: true,
    importStyles: true,
    importParagraphSpacing: true,
    importPageColor: true,
    importChangeTrackingMode: true,
    importCustomProperties: true,
    importCustomXmlParts: true,
    importDifferentOddEvenPages: true
  });
  await context.sync();
});

load(options)

オブジェクトの指定されたプロパティを読み込むコマンドを待ち行列に入れます。 プロパティを読み取る前に、context.sync() を呼び出す必要があります。

load(options?: Word.Interfaces.DocumentLoadOptions): Word.Document;

パラメーター

options
Word.Interfaces.DocumentLoadOptions

読み込むオブジェクトのプロパティのオプションを提供します。

戻り値

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the document.
    const thisDocument = context.document;
    
    // Queue a command to load content control properties.
    thisDocument.load('contentControls/id, contentControls/text, contentControls/tag');
    
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (thisDocument.contentControls.items.length !== 0) {
        for (let i = 0; i < thisDocument.contentControls.items.length; i++) {
            console.log(thisDocument.contentControls.items[i].id);
            console.log(thisDocument.contentControls.items[i].text);
            console.log(thisDocument.contentControls.items[i].tag);
        }
    } else {
        console.log('No content controls in this document.');
    }
});

load(propertyNames)

オブジェクトの指定されたプロパティを読み込むコマンドを待ち行列に入れます。 プロパティを読み取る前に、context.sync() を呼び出す必要があります。

load(propertyNames?: string | string[]): Word.Document;

パラメーター

propertyNames

string | string[]

読み込むプロパティを指定するコンマ区切り文字列または文字列の配列。

戻り値

load(propertyNamesAndPaths)

オブジェクトの指定されたプロパティを読み込むコマンドを待ち行列に入れます。 プロパティを読み取る前に、context.sync() を呼び出す必要があります。

load(propertyNamesAndPaths?: {
            select?: string;
            expand?: string;
        }): Word.Document;

パラメーター

propertyNamesAndPaths

{ select?: string; expand?: string; }

propertyNamesAndPaths.select は、読み込むプロパティを指定するコンマ区切り文字列で propertyNamesAndPaths.expand 、読み込むナビゲーション プロパティを指定するコンマ区切りの文字列です。

戻り値

save(saveBehavior, fileName)

ドキュメントを保存します。

save(saveBehavior?: Word.SaveBehavior, fileName?: string): void;

パラメーター

saveBehavior
Word.SaveBehavior

省略可能です。 保存動作は、'Save' または 'Prompt' である必要があります。 既定値は 'Save' です。

fileName

string

オプション。 ファイル名 (ファイル拡張子を除外)。 新しいドキュメントに対してのみ有効になります。

戻り値

void

注釈

[ API セット: WordApi 1.1 ]

注: パラメーターと fileName パラメーターは saveBehavior WordApi 1.5 で導入されました。

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the document.
    const thisDocument = context.document;

    // Queue a command to load the document save state (on the saved property).
    thisDocument.load('saved');    
    
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
        
    if (thisDocument.saved === false) {
        // Queue a command to save this document.
        thisDocument.save();
        
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Saved the document');
    } else {
        console.log('The document has not changed since the last save.');
    }
});

save(saveBehaviorString, fileName)

ドキュメントを保存します。

save(saveBehaviorString?: "Save" | "Prompt", fileName?: string): void;

パラメーター

saveBehaviorString

"Save" | "Prompt"

オプション。 保存動作は、'Save' または 'Prompt' である必要があります。 既定値は 'Save' です。

fileName

string

省略可能です。 ファイル名 (ファイル拡張子を除外)。 新しいドキュメントに対してのみ有効になります。

戻り値

void

注釈

[ API セット: WordApi 1.1 ]

注: パラメーターと fileName パラメーターは saveBehavior WordApi 1.5 で導入されました。

search(searchText, searchOptions)

指定した検索オプションを使用して、ドキュメント全体のスコープで検索を実行します。 検索結果は、範囲オブジェクトのコレクションです。

search(searchText: string, searchOptions?: Word.SearchOptions | {
            ignorePunct?: boolean;
            ignoreSpace?: boolean;
            matchCase?: boolean;
            matchPrefix?: boolean;
            matchSuffix?: boolean;
            matchWholeWord?: boolean;
            matchWildcards?: boolean;
        }): Word.RangeCollection;

パラメーター

searchText

string

searchOptions

Word.SearchOptions | { ignorePunct?: boolean; ignoreSpace?: boolean; matchCase?: boolean; matchPrefix?: boolean; matchSuffix?: boolean; matchWholeWord?: boolean; matchWildcards?: boolean; }

戻り値

注釈

[ API セット: WordApi 1.7 ]

set(properties, options)

オブジェクトの複数のプロパティを同時に設定します。 適切なプロパティを持つプレーン オブジェクトまたは同じ型の別の API オブジェクトを渡すことができます。

set(properties: Interfaces.DocumentUpdateData, options?: OfficeExtension.UpdateOptions): void;

パラメーター

properties
Word.Interfaces.DocumentUpdateData

メソッドが呼び出されるオブジェクトのプロパティに等形的に構造化されたプロパティを持つ JavaScript オブジェクト。

options
OfficeExtension.UpdateOptions

properties オブジェクトが読み取り専用プロパティを設定しようとした場合にエラーを抑制するオプションを提供します。

戻り値

void

set(properties)

既存の読み込まれたオブジェクトに基づいて、オブジェクトに複数のプロパティを同時に設定します。

set(properties: Word.Document): void;

パラメーター

properties
Word.Document

戻り値

void

toJSON()

API オブジェクトが に渡されたときにより便利な出力を提供するために、JavaScript toJSON() メソッドを JSON.stringify()オーバーライドします。 (JSON.stringifyさらに、渡される オブジェクトの メソッドを呼び出toJSONします)。一方、元のWord。Document オブジェクトは API オブジェクトです。メソッドは、元のtoJSONオブジェクトから読み込まれた子プロパティの浅いコピーを含むプレーンな JavaScript オブジェクト (としてWord.Interfaces.DocumentData型指定) を返します。

toJSON(): Word.Interfaces.DocumentData;

戻り値

track()

ドキュメントの環境変更に基づいて自動的に調整する目的でオブジェクトを追跡します。 この呼び出しは、context.trackedObjects.add(thisObject)の短縮形です。 このオブジェクトを呼び出しで .sync 使用していて、".run" バッチのシーケンシャル実行の外部で使用していて、プロパティを設定するとき、またはオブジェクトのメソッドを呼び出すときに "InvalidObjectPath" エラーが発生する場合は、オブジェクトが最初に作成されたときに追跡対象のオブジェクト コレクションにオブジェクトを追加する必要があります。 このオブジェクトがコレクションの一部である場合は、親コレクションも追跡する必要があります。

track(): Word.Document;

戻り値

untrack()

前に追跡されていた場合、このオブジェクトに関連付けられているメモリを解放します。 この呼び出しは、context.trackedObjects.remove(thisObject)の短縮形です。 追跡対象オブジェクトが多いとホスト アプリケーションの動作が遅くなります。追加したオブジェクトが不要になったら、必ずそれを解放してください。 メモリ解放が有効になる前に を呼び出す context.sync() 必要があります。

untrack(): Word.Document;

戻り値

イベントの詳細

onAnnotationClicked

ユーザーが注釈をクリック (または Alt + Down を使用して選択) したときに発生します。

readonly onAnnotationClicked: OfficeExtension.EventHandlers<Word.AnnotationClickedEventArgs>;

イベントの種類

注釈

[ API セット: WordApi 1.7 ]

onAnnotationHovered

ユーザーが注釈の上にカーソルを合わせると発生します。

readonly onAnnotationHovered: OfficeExtension.EventHandlers<Word.AnnotationHoveredEventArgs>;

イベントの種類

注釈

[ API セット: WordApi 1.7 ]

onAnnotationInserted

ユーザーが 1 つ以上の注釈を追加するときに発生します。

readonly onAnnotationInserted: OfficeExtension.EventHandlers<Word.AnnotationInsertedEventArgs>;

イベントの種類

注釈

[ API セット: WordApi 1.7 ]

onAnnotationPopupAction

注意

この API は開発者向けにプレビューとして提供されており、寄せられたフィードバックにもとづいて変更される場合があります。 この API は運用環境で使用しないでください。

ユーザーが注釈ポップアップ メニューでアクションを実行したときに発生します。

readonly onAnnotationPopupAction: OfficeExtension.EventHandlers<Word.AnnotationPopupActionEventArgs>;

イベントの種類

注釈

[ API セット: WordApi BETA (プレビューのみ) ]

onAnnotationRemoved

ユーザーが 1 つ以上の注釈を削除するときに発生します。

readonly onAnnotationRemoved: OfficeExtension.EventHandlers<Word.AnnotationRemovedEventArgs>;

イベントの種類

注釈

[ API セット: WordApi 1.7 ]

onContentControlAdded

コンテンツ コントロールが追加されたときに発生します。 ハンドラーで context.sync() を実行して、新しいコンテンツ コントロールのプロパティを取得します。

readonly onContentControlAdded: OfficeExtension.EventHandlers<Word.ContentControlAddedEventArgs>;

イベントの種類

注釈

[ API セット: WordApi 1.5 ]

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-onadded-event.yaml

// Registers the onAdded event handler on the document.
await Word.run(async (context) => {
  eventContext = context.document.onContentControlAdded.add(contentControlAdded);
  await context.sync();

  console.log("Added event handler for when content controls are added.");
});

...

async function contentControlAdded(event: Word.ContentControlAddedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.eventType} event detected. IDs of content controls that were added:`);
    console.log(event.ids);
  });
}

onParagraphAdded

ユーザーが新しい段落を追加するときに発生します。

readonly onParagraphAdded: OfficeExtension.EventHandlers<Word.ParagraphAddedEventArgs>;

イベントの種類

注釈

[ API セット: WordApi 1.6 ]

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/onadded-event.yaml

// Registers the onParagraphAdded event handler on the document.
await Word.run(async (context) => {
  eventContext = context.document.onParagraphAdded.add(paragraphAdded);
  await context.sync();

  console.log("Added event handler for when paragraphs are added.");
});

...

async function paragraphAdded(event: Word.ParagraphAddedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.type} event detected. IDs of paragraphs that were added:`);
    console.log(event.uniqueLocalIds);
  });
}

onParagraphChanged

ユーザーが段落を変更したときに発生します。

readonly onParagraphChanged: OfficeExtension.EventHandlers<Word.ParagraphChangedEventArgs>;

イベントの種類

注釈

[ API セット: WordApi 1.6 ]

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/onchanged-event.yaml

// Registers the onParagraphChanged event handler on the document.
await Word.run(async (context) => {
  eventContext = context.document.onParagraphChanged.add(paragraphChanged);
  await context.sync();

  console.log("Added event handler for when content is changed in paragraphs.");
});

...

async function paragraphChanged(event: Word.ParagraphChangedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.type} event detected. IDs of paragraphs where content was changed:`);
    console.log(event.uniqueLocalIds);
  });
}

onParagraphDeleted

ユーザーが段落を削除したときに発生します。

readonly onParagraphDeleted: OfficeExtension.EventHandlers<Word.ParagraphDeletedEventArgs>;

イベントの種類

注釈

[ API セット: WordApi 1.6 ]

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/ondeleted-event.yaml

// Registers the onParagraphDeleted event handler on the document.
await Word.run(async (context) => {
  eventContext = context.document.onParagraphDeleted.add(paragraphDeleted);
  await context.sync();

  console.log("Added event handlers for when paragraphs are deleted.");
});

...

async function paragraphDeleted(event: Word.ParagraphDeletedEventArgs) {
  await Word.run(async (context) => {
    console.log(`${event.type} event detected. IDs of paragraphs that were deleted:`);
    console.log(event.uniqueLocalIds);
  });
}