Word.Body class

Représente le corps d’un document ou d’une section.

Extends

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Propriétés

contentControls

Obtient la collection d’objets de contrôle de contenu de texte enrichi dans le corps.

context

Contexte de requête associé à l’objet . Cela connecte le processus du complément au processus de l’application hôte Office.

endnotes

Obtient la collection de notes de fin dans le corps.

fields

Obtient la collection d’objets de champ dans le corps.

font

Obtient le format de texte du corps. Utilisez-la pour obtenir et définir le nom de la police, la taille, la couleur et d’autres propriétés.

footnotes

Obtient la collection de notes de bas de page dans le corps.

inlinePictures

Obtient la collection d’objets InlinePicture dans le corps. La collection n’inclut pas d’images flottantes.

lists

Obtient la collection d’objets list dans le corps.

paragraphs

Obtient la collection d’objets de paragraphe dans le corps.

parentBody

Obtient le corps parent du corps. Par exemple, le corps parent du corps d’une cellule de tableau peut être un en-tête. Génère une ItemNotFound erreur s’il n’y a pas de corps parent.

parentBodyOrNullObject

Obtient le corps parent du corps. Par exemple, le corps parent du corps d’une cellule de tableau peut être un en-tête. S’il n’existe pas de corps parent, cette méthode retourne un objet avec sa isNullObject propriété définie sur true. Pour plus d’informations, consultez *Méthodes et propriétés OrNullObject.

parentContentControl

Obtient le contrôle de contenu qui contient le corps. Génère une ItemNotFound erreur s’il n’existe pas de contrôle de contenu parent.

parentContentControlOrNullObject

Obtient le contrôle de contenu qui contient le corps. S’il n’existe pas de contrôle de contenu parent, cette méthode retourne un objet avec sa isNullObject propriété définie sur true. Pour plus d’informations, consultez *Méthodes et propriétés OrNullObject.

parentSection

Obtient la section parent du corps. Génère une ItemNotFound erreur s’il n’existe pas de section parente.

parentSectionOrNullObject

Obtient la section parent du corps. S’il n’existe pas de section parente, cette méthode retourne un objet avec sa isNullObject propriété définie sur true. Pour plus d’informations, consultez *Méthodes et propriétés OrNullObject.

style

Spécifie le nom du style pour le corps. Utilisez cette propriété pour les noms des styles personnalisés et localisés. Pour utiliser les styles prédéfinis qui sont portables entre différents paramètres régionaux, voir la propriété « styleBuiltIn ».

styleBuiltIn

Spécifie le nom de style intégré pour le corps. Utilisez cette propriété pour les styles intégrés qui sont portables entre les paramètres régionaux. Pour utiliser des styles personnalisés ou des noms de style localisés, consultez la propriété « style ».

tables

Obtient la collection d’objets table dans le corps.

text

Obtient le texte du corps. Utilisez la méthode insertText pour insérer du texte.

type

Obtient le type du corps. Le type peut être « MainDoc », « Section », « Header », « Footer » ou « TableCell ». Les types supplémentaires « Footnote », « Endnote » et « NoteItem » sont pris en charge dans WordAPIOnline 1.1 et versions ultérieures.

Méthodes

clear()

Efface le contenu de l’objet de corps. L’utilisateur peut effectuer l’opération d’annulation sur le contenu effacé.

getComments()

Obtient les commentaires associés au corps.

getContentControls(options)

Obtient les contrôles de contenu actuellement pris en charge dans le corps.

getHtml()

Obtient une représentation HTML de l’objet body. En cas de rendu dans une page web ou une visionneuse HTML, la mise en forme correspond à une correspondance proche, mais pas exacte, pour la mise en forme du document. Cette méthode ne retourne pas exactement le même code HTML pour le même document sur différentes plateformes (Windows, Mac, Word sur le web, etc.). Si vous avez besoin d’une fidélité exacte ou d’une cohérence entre les plateformes, utilisez Body.getOoxml() et convertissez le code XML retourné au format HTML.

getOoxml()

Obtient la représentation OOXML (Office Open XML) de l’objet de corps.

getRange(rangeLocation)

Obtient la totalité du corps, ou le point de début ou de fin du corps, sous la forme d’une plage.

getReviewedText(changeTrackingVersion)

Obtient le texte révisé en fonction de la sélection de ChangeTrackingVersion.

getReviewedText(changeTrackingVersionString)

Obtient le texte révisé en fonction de la sélection de ChangeTrackingVersion.

getTrackedChanges()

Obtient la collection des objets TrackedChange dans le corps.

insertBreak(breakType, insertLocation)

Insère un saut à l’emplacement spécifié du document principal.

insertContentControl(contentControlType)

Encapsule l’objet Body avec un contrôle de contenu.

insertFileFromBase64(base64File, insertLocation)

Insère un document dans le corps à l’emplacement spécifié.

insertHtml(html, insertLocation)

Insère du code HTML à l’emplacement spécifié.

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Insère une image dans le corps à l’emplacement spécifié.

insertOoxml(ooxml, insertLocation)

Insère du code OOXML à l’emplacement spécifié.

insertParagraph(paragraphText, insertLocation)

Insère un paragraphe à l’emplacement spécifié.

insertTable(rowCount, columnCount, insertLocation, values)

Insère un tableau avec le nombre spécifié de lignes et de colonnes.

insertText(text, insertLocation)

Insère du texte dans le corps à l’emplacement spécifié.

load(options)

Files d’attente de la commande pour charger les propriétés de l’objet spécifié. Vous devez contacter context.sync() avant de lire les propriétés.

load(propertyNames)

Files d’attente de la commande pour charger les propriétés de l’objet spécifié. Vous devez contacter context.sync() avant de lire les propriétés.

load(propertyNamesAndPaths)

Files d’attente de la commande pour charger les propriétés de l’objet spécifié. Vous devez contacter context.sync() avant de lire les propriétés.

search(searchText, searchOptions)

Effectue une recherche avec l’objet SearchOptions spécifié dans l’étendue de l’objet body. Les résultats de la recherche sont un ensemble d’objets de plage.

select(selectionMode)

Sélectionne le corps et y accède via l’interface utilisateur de Word.

select(selectionModeString)

Sélectionne le corps et y accède via l’interface utilisateur de Word.

set(properties, options)

Définit plusieurs propriétés d’un objet en même temps. Vous pouvez passer un objet brut avec les propriétés appropriées ou un autre objet API du même type.

set(properties)

Définit plusieurs propriétés sur l’objet en même temps, en fonction d’un objet chargé existant.

toJSON()

Remplace la méthode JavaScript toJSON() afin de fournir une sortie plus utile lorsqu’un objet API est passé à JSON.stringify(). (JSON.stringifyappelle à son tour la toJSON méthode de l’objet qui lui est passé.) Alors que le Word d’origine. L’objet Body est un objet API. La toJSON méthode renvoie un objet JavaScript brut (typé en tant Word.Interfaces.BodyDataque ) qui contient des copies superficielles de toutes les propriétés enfants chargées à partir de l’objet d’origine.

track()

Effectuer le suivi de l’objet pour l’ajustement automatique en fonction environnant des modifications dans le document. Cet appel est un raccourci pour context.trackedObjects.add(thisObject). Si vous utilisez cet objet sur des .sync appels et en dehors de l’exécution séquentielle d’un lot « .run », et que vous obtenez une erreur « InvalidObjectPath » lors de la définition d’une propriété ou de l’appel d’une méthode sur l’objet, vous devez ajouter l’objet à la collection d’objets suivie lors de la première création de l’objet. Si cet objet fait partie d’une collection, vous devez également suivre la collection parente.

untrack()

Publication mémoire associée à cet objet si elle a été précédemment suivie. Cet appel est abrégé pour context.trackedObjects.remove(thisObject). Vous rencontrez de nombreux objets suivies ralentit l’application hôte, donc n’oubliez pas de libérer les objets que l'on ajoute, une fois que vous avez terminé à les utiliser. Vous devez appeler context.sync() avant que la mise en production de la mémoire ne prenne effet.

Événements

onCommentAdded

Se produit lorsque de nouveaux commentaires sont ajoutés.

onCommentChanged

Se produit lorsqu’un commentaire ou sa réponse est modifié.

onCommentDeleted

Se produit lorsque les commentaires sont supprimés.

onCommentDeselected

Se produit lorsqu’un commentaire est désélectionné.

onCommentSelected

Se produit lorsqu’un commentaire est sélectionné.

Détails de la propriété

contentControls

Obtient la collection d’objets de contrôle de contenu de texte enrichi dans le corps.

readonly contentControls: Word.ContentControlCollection;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.1 ]

context

Contexte de requête associé à l’objet . Cela connecte le processus du complément au processus de l’application hôte Office.

context: RequestContext;

Valeur de propriété

endnotes

Obtient la collection de notes de fin dans le corps.

readonly endnotes: Word.NoteItemCollection;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.5 ]

fields

Obtient la collection d’objets de champ dans le corps.

readonly fields: Word.FieldCollection;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.4 ]

Exemples

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

// Gets all fields in the document body.
await Word.run(async (context) => {
  const fields = context.document.body.fields.load("items");

  await context.sync();

  if (fields.items.length === 0) {
    console.log("No fields in this document.");
  } else {
    fields.load(["code", "result"]);
    await context.sync();

    for (let i = 0; i < fields.items.length; i++) {
      console.log(`Field ${i + 1}'s code: ${fields.items[i].code}`);
      console.log(`Field ${i + 1}'s result: ${JSON.stringify(fields.items[i].result)}`);
    }
  }
});

font

Obtient le format de texte du corps. Utilisez-la pour obtenir et définir le nom de la police, la taille, la couleur et d’autres propriétés.

readonly font: Word.Font;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Exemples

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

// Gets the style and the font size, font name, and font color properties on the body object.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
  // Create a proxy object for the document body.
  const body = context.document.body;

  // Queue a command to load font and style information for the document body.
  body.load("font/size, font/name, font/color, style");

  // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
  await context.sync();

  // Show font-related property values on the body object.
  const results =
    "Font size: " +
    body.font.size +
    "; Font name: " +
    body.font.name +
    "; Font color: " +
    body.font.color +
    "; Body style: " +
    body.style;

  console.log(results);
});

footnotes

Obtient la collection de notes de bas de page dans le corps.

readonly footnotes: Word.NoteItemCollection;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.5 ]

Exemples

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

// Gets the footnotes in the document body.
await Word.run(async (context) => {
  const footnotes = context.document.body.footnotes;
  footnotes.load("length");
  await context.sync();

  console.log("Number of footnotes in the document body: " + footnotes.items.length);
});

inlinePictures

Obtient la collection d’objets InlinePicture dans le corps. La collection n’inclut pas d’images flottantes.

readonly inlinePictures: Word.InlinePictureCollection;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/15-images/insert-and-get-pictures.yaml

// Gets the first image in the document.
await Word.run(async (context) => {
  const firstPicture = context.document.body.inlinePictures.getFirst();
  firstPicture.load("width, height");

  await context.sync();
  console.log(`Image dimensions: ${firstPicture.width} x ${firstPicture.height}`);
  // Get the image encoded as Base64.
  const base64 = firstPicture.getBase64ImageSrc();

  await context.sync();
  console.log(base64.value);
});

lists

Obtient la collection d’objets list dans le corps.

readonly lists: Word.ListCollection;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.3 ]

paragraphs

Obtient la collection d’objets de paragraphe dans le corps.

readonly paragraphs: Word.ParagraphCollection;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Important : les paragraphes des tableaux ne sont pas retournés pour les ensembles de conditions requises 1.1 et 1.2. À partir de l’ensemble de conditions requises 1.3, les paragraphes des tableaux sont également retournés.

Exemples

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

// Counts how many times each term appears in the document.
await Word.run(async (context) => {
  const paragraphs = context.document.body.paragraphs;
  paragraphs.load("text");
  await context.sync();

  // Split up the document text using existing spaces as the delimiter.
  let text = [];
  paragraphs.items.forEach((item) => {
    let paragraph = item.text.trim();
    if (paragraph) {
      paragraph.split(" ").forEach((term) => {
        let currentTerm = term.trim();
        if (currentTerm) {
          text.push(currentTerm);
        }
      });
    }
  });

  // Determine the list of unique terms.
  let makeTextDistinct = new Set(text);
  let distinctText = Array.from(makeTextDistinct);
  let allSearchResults = [];

  for (let i = 0; i < distinctText.length; i++) {
    let results = context.document.body.search(distinctText[i], { matchCase: true, matchWholeWord: true });
    results.load("text");

    // Map each search term with its results.
    let correlatedResults = {
      searchTerm: distinctText[i],
      hits: results
    };

    allSearchResults.push(correlatedResults);
  }

  await context.sync();

  // Display the count for each search term.
  allSearchResults.forEach((result) => {
    let length = result.hits.items.length;

    console.log("Search term: " + result.searchTerm + " => Count: " + length);
  });
});

parentBody

Obtient le corps parent du corps. Par exemple, le corps parent du corps d’une cellule de tableau peut être un en-tête. Génère une ItemNotFound erreur s’il n’y a pas de corps parent.

readonly parentBody: Word.Body;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.3 ]

parentBodyOrNullObject

Obtient le corps parent du corps. Par exemple, le corps parent du corps d’une cellule de tableau peut être un en-tête. S’il n’existe pas de corps parent, cette méthode retourne un objet avec sa isNullObject propriété définie sur true. Pour plus d’informations, consultez *Méthodes et propriétés OrNullObject.

readonly parentBodyOrNullObject: Word.Body;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.3 ]

parentContentControl

Obtient le contrôle de contenu qui contient le corps. Génère une ItemNotFound erreur s’il n’existe pas de contrôle de contenu parent.

readonly parentContentControl: Word.ContentControl;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.1 ]

parentContentControlOrNullObject

Obtient le contrôle de contenu qui contient le corps. S’il n’existe pas de contrôle de contenu parent, cette méthode retourne un objet avec sa isNullObject propriété définie sur true. Pour plus d’informations, consultez *Méthodes et propriétés OrNullObject.

readonly parentContentControlOrNullObject: Word.ContentControl;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.3 ]

parentSection

Obtient la section parent du corps. Génère une ItemNotFound erreur s’il n’existe pas de section parente.

readonly parentSection: Word.Section;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.3 ]

parentSectionOrNullObject

Obtient la section parent du corps. S’il n’existe pas de section parente, cette méthode retourne un objet avec sa isNullObject propriété définie sur true. Pour plus d’informations, consultez *Méthodes et propriétés OrNullObject.

readonly parentSectionOrNullObject: Word.Section;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.3 ]

style

Spécifie le nom du style pour le corps. Utilisez cette propriété pour les noms des styles personnalisés et localisés. Pour utiliser les styles prédéfinis qui sont portables entre différents paramètres régionaux, voir la propriété « styleBuiltIn ».

style: string;

Valeur de propriété

string

Remarques

[ Ensemble d’API : WordApi 1.1 ]

styleBuiltIn

Spécifie le nom de style intégré pour le corps. Utilisez cette propriété pour les styles intégrés qui sont portables entre les paramètres régionaux. Pour utiliser des styles personnalisés ou des noms de style localisés, consultez la propriété « style ».

styleBuiltIn: Word.BuiltInStyleName | "Other" | "Normal" | "Heading1" | "Heading2" | "Heading3" | "Heading4" | "Heading5" | "Heading6" | "Heading7" | "Heading8" | "Heading9" | "Toc1" | "Toc2" | "Toc3" | "Toc4" | "Toc5" | "Toc6" | "Toc7" | "Toc8" | "Toc9" | "FootnoteText" | "Header" | "Footer" | "Caption" | "FootnoteReference" | "EndnoteReference" | "EndnoteText" | "Title" | "Subtitle" | "Hyperlink" | "Strong" | "Emphasis" | "NoSpacing" | "ListParagraph" | "Quote" | "IntenseQuote" | "SubtleEmphasis" | "IntenseEmphasis" | "SubtleReference" | "IntenseReference" | "BookTitle" | "Bibliography" | "TocHeading" | "TableGrid" | "PlainTable1" | "PlainTable2" | "PlainTable3" | "PlainTable4" | "PlainTable5" | "TableGridLight" | "GridTable1Light" | "GridTable1Light_Accent1" | "GridTable1Light_Accent2" | "GridTable1Light_Accent3" | "GridTable1Light_Accent4" | "GridTable1Light_Accent5" | "GridTable1Light_Accent6" | "GridTable2" | "GridTable2_Accent1" | "GridTable2_Accent2" | "GridTable2_Accent3" | "GridTable2_Accent4" | "GridTable2_Accent5" | "GridTable2_Accent6" | "GridTable3" | "GridTable3_Accent1" | "GridTable3_Accent2" | "GridTable3_Accent3" | "GridTable3_Accent4" | "GridTable3_Accent5" | "GridTable3_Accent6" | "GridTable4" | "GridTable4_Accent1" | "GridTable4_Accent2" | "GridTable4_Accent3" | "GridTable4_Accent4" | "GridTable4_Accent5" | "GridTable4_Accent6" | "GridTable5Dark" | "GridTable5Dark_Accent1" | "GridTable5Dark_Accent2" | "GridTable5Dark_Accent3" | "GridTable5Dark_Accent4" | "GridTable5Dark_Accent5" | "GridTable5Dark_Accent6" | "GridTable6Colorful" | "GridTable6Colorful_Accent1" | "GridTable6Colorful_Accent2" | "GridTable6Colorful_Accent3" | "GridTable6Colorful_Accent4" | "GridTable6Colorful_Accent5" | "GridTable6Colorful_Accent6" | "GridTable7Colorful" | "GridTable7Colorful_Accent1" | "GridTable7Colorful_Accent2" | "GridTable7Colorful_Accent3" | "GridTable7Colorful_Accent4" | "GridTable7Colorful_Accent5" | "GridTable7Colorful_Accent6" | "ListTable1Light" | "ListTable1Light_Accent1" | "ListTable1Light_Accent2" | "ListTable1Light_Accent3" | "ListTable1Light_Accent4" | "ListTable1Light_Accent5" | "ListTable1Light_Accent6" | "ListTable2" | "ListTable2_Accent1" | "ListTable2_Accent2" | "ListTable2_Accent3" | "ListTable2_Accent4" | "ListTable2_Accent5" | "ListTable2_Accent6" | "ListTable3" | "ListTable3_Accent1" | "ListTable3_Accent2" | "ListTable3_Accent3" | "ListTable3_Accent4" | "ListTable3_Accent5" | "ListTable3_Accent6" | "ListTable4" | "ListTable4_Accent1" | "ListTable4_Accent2" | "ListTable4_Accent3" | "ListTable4_Accent4" | "ListTable4_Accent5" | "ListTable4_Accent6" | "ListTable5Dark" | "ListTable5Dark_Accent1" | "ListTable5Dark_Accent2" | "ListTable5Dark_Accent3" | "ListTable5Dark_Accent4" | "ListTable5Dark_Accent5" | "ListTable5Dark_Accent6" | "ListTable6Colorful" | "ListTable6Colorful_Accent1" | "ListTable6Colorful_Accent2" | "ListTable6Colorful_Accent3" | "ListTable6Colorful_Accent4" | "ListTable6Colorful_Accent5" | "ListTable6Colorful_Accent6" | "ListTable7Colorful" | "ListTable7Colorful_Accent1" | "ListTable7Colorful_Accent2" | "ListTable7Colorful_Accent3" | "ListTable7Colorful_Accent4" | "ListTable7Colorful_Accent5" | "ListTable7Colorful_Accent6";

Valeur de propriété

Word.BuiltInStyleName | "Other" | "Normal" | "Heading1" | "Heading2" | "Heading3" | "Heading4" | "Heading5" | "Heading6" | "Heading7" | "Heading8" | "Heading9" | "Toc1" | "Toc2" | "Toc3" | "Toc4" | "Toc5" | "Toc6" | "Toc7" | "Toc8" | "Toc9" | "FootnoteText" | "Header" | "Footer" | "Caption" | "FootnoteReference" | "EndnoteReference" | "EndnoteText" | "Title" | "Subtitle" | "Hyperlink" | "Strong" | "Emphasis" | "NoSpacing" | "ListParagraph" | "Quote" | "IntenseQuote" | "SubtleEmphasis" | "IntenseEmphasis" | "SubtleReference" | "IntenseReference" | "BookTitle" | "Bibliography" | "TocHeading" | "TableGrid" | "PlainTable1" | "PlainTable2" | "PlainTable3" | "PlainTable4" | "PlainTable5" | "TableGridLight" | "GridTable1Light" | "GridTable1Light_Accent1" | "GridTable1Light_Accent2" | "GridTable1Light_Accent3" | "GridTable1Light_Accent4" | "GridTable1Light_Accent5" | "GridTable1Light_Accent6" | "GridTable2" | "GridTable2_Accent1" | "GridTable2_Accent2" | "GridTable2_Accent3" | "GridTable2_Accent4" | "GridTable2_Accent5" | "GridTable2_Accent6" | "GridTable3" | "GridTable3_Accent1" | "GridTable3_Accent2" | "GridTable3_Accent3" | "GridTable3_Accent4" | "GridTable3_Accent5" | "GridTable3_Accent6" | "GridTable4" | "GridTable4_Accent1" | "GridTable4_Accent2" | "GridTable4_Accent3" | "GridTable4_Accent4" | "GridTable4_Accent5" | "GridTable4_Accent6" | "GridTable5Dark" | "GridTable5Dark_Accent1" | "GridTable5Dark_Accent2" | "GridTable5Dark_Accent3" | "GridTable5Dark_Accent4" | "GridTable5Dark_Accent5" | "GridTable5Dark_Accent6" | "GridTable6Colorful" | "GridTable6Colorful_Accent1" | "GridTable6Colorful_Accent2" | "GridTable6Colorful_Accent3" | "GridTable6Colorful_Accent4" | "GridTable6Colorful_Accent5" | "GridTable6Colorful_Accent6" | "GridTable7Colorful" | "GridTable7Colorful_Accent1" | "GridTable7Colorful_Accent2" | "GridTable7Colorful_Accent3" | "GridTable7Colorful_Accent4" | "GridTable7Colorful_Accent5" | "GridTable7Colorful_Accent6" | "ListTable1Light" | "ListTable1Light_Accent1" | "ListTable1Light_Accent2" | "ListTable1Light_Accent3" | "ListTable1Light_Accent4" | "ListTable1Light_Accent5" | "ListTable1Light_Accent6" | "ListTable2" | "ListTable2_Accent1" | "ListTable2_Accent2" | "ListTable2_Accent3" | "ListTable2_Accent4" | "ListTable2_Accent5" | "ListTable2_Accent6" | "ListTable3" | "ListTable3_Accent1" | "ListTable3_Accent2" | "ListTable3_Accent3" | "ListTable3_Accent4" | "ListTable3_Accent5" | "ListTable3_Accent6" | "ListTable4" | "ListTable4_Accent1" | "ListTable4_Accent2" | "ListTable4_Accent3" | "ListTable4_Accent4" | "ListTable4_Accent5" | "ListTable4_Accent6" | "ListTable5Dark" | "ListTable5Dark_Accent1" | "ListTable5Dark_Accent2" | "ListTable5Dark_Accent3" | "ListTable5Dark_Accent4" | "ListTable5Dark_Accent5" | "ListTable5Dark_Accent6" | "ListTable6Colorful" | "ListTable6Colorful_Accent1" | "ListTable6Colorful_Accent2" | "ListTable6Colorful_Accent3" | "ListTable6Colorful_Accent4" | "ListTable6Colorful_Accent5" | "ListTable6Colorful_Accent6" | "ListTable7Colorful" | "ListTable7Colorful_Accent1" | "ListTable7Colorful_Accent2" | "ListTable7Colorful_Accent3" | "ListTable7Colorful_Accent4" | "ListTable7Colorful_Accent5" | "ListTable7Colorful_Accent6"

Remarques

[ Ensemble d’API : WordApi 1.3 ]

tables

Obtient la collection d’objets table dans le corps.

readonly tables: Word.TableCollection;

Valeur de propriété

Remarques

[ Ensemble d’API : WordApi 1.3 ]

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/40-tables/table-cell-access.yaml

// Gets the content of the first cell in the first table.
await Word.run(async (context) => {
  const firstCell = context.document.body.tables.getFirst().getCell(0, 0).body;
  firstCell.load("text");

  await context.sync();
  console.log("First cell's text is: " + firstCell.text);
});

text

Obtient le texte du corps. Utilisez la méthode insertText pour insérer du texte.

readonly text: string;

Valeur de propriété

string

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Exemples

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

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

  // Queue a command to load the text in document body.
  body.load("text");

  // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
  await context.sync();

  console.log("Body contents (text): " + body.text);
});

type

Obtient le type du corps. Le type peut être « MainDoc », « Section », « Header », « Footer » ou « TableCell ». Les types supplémentaires « Footnote », « Endnote » et « NoteItem » sont pris en charge dans WordAPIOnline 1.1 et versions ultérieures.

readonly type: Word.BodyType | "Unknown" | "MainDoc" | "Section" | "Header" | "Footer" | "TableCell" | "Footnote" | "Endnote" | "NoteItem";

Valeur de propriété

Word.BodyType | "Unknown" | "MainDoc" | "Section" | "Header" | "Footer" | "TableCell" | "Footnote" | "Endnote" | "NoteItem"

Remarques

[ Ensemble d’API : WordApi 1.3 ]

Exemples

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

// Gets the referenced note's item type and body type, which are both "Footnote".
await Word.run(async (context) => {
  const footnotes = context.document.body.footnotes;
  footnotes.load("items");
  await context.sync();

  const referenceNumber = $("#input-reference").val();
  const mark = (referenceNumber as number) - 1;
  const item = footnotes.items[mark];
  console.log(`Note type of footnote ${referenceNumber}: ${item.type}`);

  item.body.load("type");
  await context.sync();

  console.log(`Body type of note: ${item.body.type}`);
});

Détails de la méthode

clear()

Efface le contenu de l’objet de corps. L’utilisateur peut effectuer l’opération d’annulation sur le contenu effacé.

clear(): void;

Retours

void

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Exemples

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

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

  // Queue a command to clear the contents of the body.
  body.clear();

  console.log("Cleared the body contents.");
});

// The Silly stories add-in sample shows how the clear method can be used to clear the contents of a document.
// https://aka.ms/sillystorywordaddin

getComments()

Obtient les commentaires associés au corps.

getComments(): Word.CommentCollection;

Retours

Remarques

[ Ensemble d’API : WordApi 1.4 ]

Exemples

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

// Gets the comments in the document body.
await Word.run(async (context) => {
  const comments = context.document.body.getComments();

  // Load objects for display in Script Lab console.
  comments.load();
  await context.sync();

  console.log("All comments:");
  console.log(comments);
});

getContentControls(options)

Obtient les contrôles de contenu actuellement pris en charge dans le corps.

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

Paramètres

options
Word.ContentControlOptions

Facultatif. Options qui définissent les contrôles de contenu qui sont retournés.

Retours

Remarques

[ Ensemble d’API : WordApi 1.5 ]

Important : si des types spécifiques sont fournis dans le paramètre options, seuls les contrôles de contenu des types pris en charge sont retournés. N’oubliez pas qu’une exception sera levée à l’aide de méthodes d’un Word générique. ContentControl qui ne sont pas pertinents pour le type spécifique. Avec le temps, d’autres types de contrôles de contenu peuvent être pris en charge. Par conséquent, votre complément doit demander et gérer des types spécifiques de contrôles de contenu.

getHtml()

Obtient une représentation HTML de l’objet body. En cas de rendu dans une page web ou une visionneuse HTML, la mise en forme correspond à une correspondance proche, mais pas exacte, pour la mise en forme du document. Cette méthode ne retourne pas exactement le même code HTML pour le même document sur différentes plateformes (Windows, Mac, Word sur le web, etc.). Si vous avez besoin d’une fidélité exacte ou d’une cohérence entre les plateformes, utilisez Body.getOoxml() et convertissez le code XML retourné au format HTML.

getHtml(): OfficeExtension.ClientResult<string>;

Retours

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Exemples

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

// Gets the HTML that represents the content of the body.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
  // Create a proxy object for the document body.
  const body = context.document.body;

  // Queue a command to get the HTML contents of the body.
  const bodyHTML = body.getHtml();

  // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
  await context.sync();

  console.log("Body contents (HTML): " + bodyHTML.value);
});

getOoxml()

Obtient la représentation OOXML (Office Open XML) de l’objet de corps.

getOoxml(): OfficeExtension.ClientResult<string>;

Retours

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Exemples

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

// Gets the OOXML that represents the content of the body.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
  // Create a proxy object for the document body.
  const body = context.document.body;

  // Queue a command to get the OOXML contents of the body.
  const bodyOOXML = body.getOoxml();

  // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
  await context.sync();

  console.log("Body contents (OOXML): " + bodyOOXML.value);
});

getRange(rangeLocation)

Obtient la totalité du corps, ou le point de début ou de fin du corps, sous la forme d’une plage.

getRange(rangeLocation?: Word.RangeLocation.whole | Word.RangeLocation.start | Word.RangeLocation.end | Word.RangeLocation.after | Word.RangeLocation.content | "Whole" | "Start" | "End" | "After" | "Content"): Word.Range;

Paramètres

rangeLocation

whole | start | end | after | content | "Whole" | "Start" | "End" | "After" | "Content"

Facultatif. L’emplacement de la plage doit être « Entier », « Début », « Fin », « Après » ou « Contenu ».

Retours

Remarques

[ Ensemble d’API : WordApi 1.3 ]

getReviewedText(changeTrackingVersion)

Obtient le texte révisé en fonction de la sélection de ChangeTrackingVersion.

getReviewedText(changeTrackingVersion?: Word.ChangeTrackingVersion): OfficeExtension.ClientResult<string>;

Paramètres

changeTrackingVersion
Word.ChangeTrackingVersion

Facultatif. La valeur doit être « Original » ou « Current ». La valeur par défaut est « Current ».

Retours

Remarques

[ Ensemble d’API : WordApi 1.4 ]

getReviewedText(changeTrackingVersionString)

Obtient le texte révisé en fonction de la sélection de ChangeTrackingVersion.

getReviewedText(changeTrackingVersionString?: "Original" | "Current"): OfficeExtension.ClientResult<string>;

Paramètres

changeTrackingVersionString

"Original" | "Current"

Facultatif. La valeur doit être « Original » ou « Current ». La valeur par défaut est « Current ».

Retours

Remarques

[ Ensemble d’API : WordApi 1.4 ]

getTrackedChanges()

Obtient la collection des objets TrackedChange dans le corps.

getTrackedChanges(): Word.TrackedChangeCollection;

Retours

Remarques

[ Ensemble d’API : WordApi 1.6 ]

Exemples

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

// Gets all tracked changes.
await Word.run(async (context) => {
  const body = context.document.body;
  const trackedChanges = body.getTrackedChanges();
  trackedChanges.load();
  await context.sync();

  console.log(trackedChanges);
});

insertBreak(breakType, insertLocation)

Insère un saut à l’emplacement spécifié du document principal.

insertBreak(breakType: Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | "Start" | "End"): void;

Paramètres

breakType

Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line"

Obligatoire. Type de saut à ajouter au corps.

insertLocation

start | end | "Start" | "End"

Obligatoire. La valeur doit être « Start » ou « End ».

Retours

void

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Exemples

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

// Inserts a page break at the beginning of the document.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
  // Create a proxy object for the document body.
  const body = context.document.body;

  // Queue a command to insert a page break at the start of the document body.
  body.insertBreak(Word.BreakType.page, Word.InsertLocation.start);

  // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
  await context.sync();

  console.log("Added a page break at the start of the document body.");
});

insertContentControl(contentControlType)

Encapsule l’objet Body avec un contrôle de contenu.

insertContentControl(contentControlType?: Word.ContentControlType.richText | Word.ContentControlType.plainText | Word.ContentControlType.checkBox | "RichText" | "PlainText" | "CheckBox"): Word.ContentControl;

Paramètres

contentControlType

richText | plainText | checkBox | "RichText" | "PlainText" | "CheckBox"

Facultatif. Type de contrôle de contenu à insérer. Doit être « RichText », « PlainText » ou « CheckBox ». La valeur par défaut est « RichText ».

Retours

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Remarque : Le contentControlType paramètre a été introduit dans WordApi 1.5. PlainText la prise en charge a été ajoutée dans WordApi 1.5. CheckBox la prise en charge a été ajoutée dans WordApi 1.7.

Exemples

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

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

  // Queue a command to wrap the body in a content control.
  body.insertContentControl();

  // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
  await context.sync();

  console.log("Wrapped the body in a content control.");
});

insertFileFromBase64(base64File, insertLocation)

Insère un document dans le corps à l’emplacement spécifié.

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

Paramètres

base64File

string

Obligatoire. Contenu encodé en Base64 d’un fichier .docx.

insertLocation

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

Obligatoire. La valeur doit être « Replace », « Start » ou « End ».

Retours

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Remarque : l’insertion n’est pas prise en charge si le document inséré contient un contrôle ActiveX (probablement dans un champ de formulaire). Envisagez de remplacer un tel champ de formulaire par un contrôle de contenu ou une autre option appropriée pour votre scénario.

Exemples

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

// Inserts the body from the external document at the beginning of this document.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
  // Create a proxy object for the document body.
  const body = context.document.body;

  // Queue a command to insert the Base64-encoded string representation of the body of the selected .docx file at the beginning of the current document.
  body.insertFileFromBase64(externalDocument, Word.InsertLocation.start);

  // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
  await context.sync();

  console.log("Added Base64-encoded text to the beginning of the document body.");
});

insertHtml(html, insertLocation)

Insère du code HTML à l’emplacement spécifié.

insertHtml(html: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Paramètres

html

string

Obligatoire. Code HTML à insérer dans le document.

insertLocation

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

Obligatoire. La valeur doit être « Replace », « Start » ou « End ».

Retours

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Exemples

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

// Inserts the HTML at the beginning of this document.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
  // Create a proxy object for the document body.
  const body = context.document.body;

  // Queue a command to insert HTML at the beginning of the document.
  body.insertHtml("<strong>This is text inserted with body.insertHtml()</strong>", Word.InsertLocation.start);

  // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
  await context.sync();

  console.log("HTML added to the beginning of the document body.");
});

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Insère une image dans le corps à l’emplacement spécifié.

insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | "Start" | "End"): Word.InlinePicture;

Paramètres

base64EncodedImage

string

Obligatoire. Image encodée en Base64 à insérer dans le corps.

insertLocation

start | end | "Start" | "End"

Obligatoire. La valeur doit être « Start » ou « End ».

Retours

Remarques

[ Ensemble d’API : WordApi 1.2 ]

Exemples

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

// Inserts an image inline at the beginning of this document.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
  // Create a proxy object for the document body.
  const body = context.document.body;

  // Base64-encoded image to insert inline.
  const base64EncodedImg =
    "iVBORw0KGgoAAAANSUhEUgAAAB4AAAANCAIAAAAxEEnAAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACFSURBVDhPtY1BEoQwDMP6/0+XgIMTBAeYoTqso9Rkx1zG+tNj1H94jgGzeNSjteO5vtQQuG2seO0av8LzGbe3anzRoJ4ybm/VeKEerAEbAUpW4aWQCmrGFWykRzGBCnYy2ha3oAIq2MloW9yCCqhgJ6NtcQsqoIKdjLbFLaiACnYyf2fODbrjZcXfr2F4AAAAAElFTkSuQmCC";

  // Queue a command to insert a Base64-encoded image at the beginning of the current document.
  body.insertInlinePictureFromBase64(base64EncodedImg, Word.InsertLocation.start);

  // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
  await context.sync();

  console.log("Added a Base64-encoded image to the beginning of the document body.");
});

insertOoxml(ooxml, insertLocation)

Insère du code OOXML à l’emplacement spécifié.

insertOoxml(ooxml: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Paramètres

ooxml

string

Obligatoire. Code OOXML à insérer.

insertLocation

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

Obligatoire. La valeur doit être « Replace », « Start » ou « End ».

Retours

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Exemples

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

// Inserts OOXML at the beginning of this document.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
  // Create a proxy object for the document body.
  const body = context.document.body;

  // Queue a command to insert OOXML at the beginning of the body.
  body.insertOoxml(
    "<pkg:package xmlns:pkg='http://schemas.microsoft.com/office/2006/xmlPackage'><pkg:part pkg:name='/_rels/.rels' pkg:contentType='application/vnd.openxmlformats-package.relationships+xml' pkg:padding='512'><pkg:xmlData><Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships'><Relationship Id='rId1' Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument' Target='word/document.xml'/></Relationships></pkg:xmlData></pkg:part><pkg:part pkg:name='/word/document.xml' pkg:contentType='application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml'><pkg:xmlData><w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' ><w:body><w:p><w:pPr><w:spacing w:before='360' w:after='0' w:line='480' w:lineRule='auto'/><w:rPr><w:color w:val='70AD47' w:themeColor='accent6'/><w:sz w:val='28'/></w:rPr></w:pPr><w:r><w:rPr><w:color w:val='70AD47' w:themeColor='accent6'/><w:sz w:val='28'/></w:rPr><w:t>This text has formatting directly applied to achieve its font size, color, line spacing, and paragraph spacing.</w:t></w:r></w:p></w:body></w:document></pkg:xmlData></pkg:part></pkg:package>",
    Word.InsertLocation.start
  );

  // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
  await context.sync();

  console.log("Added OOXML to the beginning of the document body.");
});

// Read "Understand when and how to use Office Open XML in your Word add-in" for guidance on working with OOXML.
// https://learn.microsoft.com/office/dev/add-ins/word/create-better-add-ins-for-word-with-office-open-xml

// The Word-Add-in-DocumentAssembly sample shows how you can use this API to assemble a document.
// https://github.com/OfficeDev/Word-Add-in-DocumentAssembly

insertParagraph(paragraphText, insertLocation)

Insère un paragraphe à l’emplacement spécifié.

insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | "Start" | "End"): Word.Paragraph;

Paramètres

paragraphText

string

Obligatoire. Texte de paragraphe à insérer.

insertLocation

start | end | "Start" | "End"

Obligatoire. La valeur doit être « Start » ou « End ».

Retours

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Exemples

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

await Word.run(async (context) => {
  // Second sentence, let's insert it as a paragraph after the previously inserted one.
  const secondSentence = context.document.body.insertParagraph(
    "This is the first text with a custom style.",
    "End"
  );
  secondSentence.font.set({
    bold: false,
    italic: true,
    name: "Berlin Sans FB",
    color: "blue",
    size: 30
  });

  await context.sync();
});

insertTable(rowCount, columnCount, insertLocation, values)

Insère un tableau avec le nombre spécifié de lignes et de colonnes.

insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | "Start" | "End", values?: string[][]): Word.Table;

Paramètres

rowCount

number

Obligatoire. Nombre de lignes dans le tableau.

columnCount

number

Obligatoire. Nombre de colonnes dans le tableau.

insertLocation

start | end | "Start" | "End"

Obligatoire. La valeur doit être « Start » ou « End ».

values

string[][]

Tableau 2D facultatif. Les cellules sont remplies si les chaînes correspondantes sont spécifiées dans le tableau.

Retours

Remarques

[ Ensemble d’API : WordApi 1.3 ]

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/40-tables/table-cell-access.yaml

await Word.run(async (context) => {
  // Use a two-dimensional array to hold the initial table values.
  const data = [
    ["Tokyo", "Beijing", "Seattle"],
    ["Apple", "Orange", "Pineapple"]
  ];
  const table = context.document.body.insertTable(2, 3, "Start", data);
  table.styleBuiltIn = Word.BuiltInStyleName.gridTable5Dark_Accent2;
  table.styleFirstColumn = false;

  await context.sync();
});

insertText(text, insertLocation)

Insère du texte dans le corps à l’emplacement spécifié.

insertText(text: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Paramètres

text

string

Obligatoire. Texte à insérer.

insertLocation

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

Obligatoire. La valeur doit être « Replace », « Start » ou « End ».

Retours

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Exemples

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

// Inserts text at the beginning of this document.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
  // Create a proxy object for the document body.
  const body = context.document.body;

  // Queue a command to insert text at the beginning of the current document.
  body.insertText('This is text inserted with body.insertText()', Word.InsertLocation.start);

  // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
  await context.sync();

  console.log('Text added to the beginning of the document body.');
});

load(options)

Files d’attente de la commande pour charger les propriétés de l’objet spécifié. Vous devez contacter context.sync() avant de lire les propriétés.

load(options?: Word.Interfaces.BodyLoadOptions): Word.Body;

Paramètres

options
Word.Interfaces.BodyLoadOptions

Fournit des options pour les propriétés de l’objet à charger.

Retours

load(propertyNames)

Files d’attente de la commande pour charger les propriétés de l’objet spécifié. Vous devez contacter context.sync() avant de lire les propriétés.

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

Paramètres

propertyNames

string | string[]

Chaîne délimitée par des virgules ou tableau de chaînes qui spécifient les propriétés à charger.

Retours

load(propertyNamesAndPaths)

Files d’attente de la commande pour charger les propriétés de l’objet spécifié. Vous devez contacter context.sync() avant de lire les propriétés.

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

Paramètres

propertyNamesAndPaths

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

propertyNamesAndPaths.select est une chaîne délimitée par des virgules qui spécifie les propriétés à charger, et propertyNamesAndPaths.expand est une chaîne délimitée par des virgules qui spécifie les propriétés de navigation à charger.

Retours

search(searchText, searchOptions)

Effectue une recherche avec l’objet SearchOptions spécifié dans l’étendue de l’objet body. Les résultats de la recherche sont un ensemble d’objets de plage.

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

Paramètres

searchText

string

Obligatoire. Texte de recherche. Peut comporter un maximum de 255 caractères.

searchOptions

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

Facultatif. Options de la recherche.

Retours

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Exemples

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

// Does a basic text search and highlights matches in the document.
await Word.run(async (context) => {
  const results = context.document.body.search("Online");
  results.load("length");

  await context.sync();

  // Let's traverse the search results and highlight matches.
  for (let i = 0; i < results.items.length; i++) {
    results.items[i].font.highlightColor = "yellow";
  }

  await context.sync();
});

...

// Does a wildcard search and highlights matches in the document.
await Word.run(async (context) => {
  // Construct a wildcard expression and set matchWildcards to true in order to use wildcards.
  const results = context.document.body.search("$*.[0-9][0-9]", { matchWildcards: true });
  results.load("length");

  await context.sync();

  // Let's traverse the search results and highlight matches.
  for (let i = 0; i < results.items.length; i++) {
    results.items[i].font.highlightColor = "red";
    results.items[i].font.color = "white";
  }

  await context.sync();
});

select(selectionMode)

Sélectionne le corps et y accède via l’interface utilisateur de Word.

select(selectionMode?: Word.SelectionMode): void;

Paramètres

selectionMode
Word.SelectionMode

Facultatif. Le mode de sélection doit être « Select », « Start » ou « End ». « Select » (sélectionner) est la valeur par défaut.

Retours

void

Remarques

[ Ensemble d’API : WordApi 1.1 ]

Exemples

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

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

  // Queue a command to select the document body.
  // The Word UI will move to the selected document body.
  body.select();

  console.log("Selected the document body.");
});

select(selectionModeString)

Sélectionne le corps et y accède via l’interface utilisateur de Word.

select(selectionModeString?: "Select" | "Start" | "End"): void;

Paramètres

selectionModeString

"Select" | "Start" | "End"

Facultatif. Le mode de sélection doit être « Select », « Start » ou « End ». « Select » (sélectionner) est la valeur par défaut.

Retours

void

Remarques

[ Ensemble d’API : WordApi 1.1 ]

set(properties, options)

Définit plusieurs propriétés d’un objet en même temps. Vous pouvez passer un objet brut avec les propriétés appropriées ou un autre objet API du même type.

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

Paramètres

properties
Word.Interfaces.BodyUpdateData

Objet JavaScript avec des propriétés qui sont structurées isomorphes en fonction des propriétés de l’objet sur lequel la méthode est appelée.

options
OfficeExtension.UpdateOptions

Fournit une option permettant de supprimer les erreurs si l’objet properties tente de définir des propriétés en lecture seule.

Retours

void

set(properties)

Définit plusieurs propriétés sur l’objet en même temps, en fonction d’un objet chargé existant.

set(properties: Word.Body): void;

Paramètres

properties
Word.Body

Retours

void

toJSON()

Remplace la méthode JavaScript toJSON() afin de fournir une sortie plus utile lorsqu’un objet API est passé à JSON.stringify(). (JSON.stringifyappelle à son tour la toJSON méthode de l’objet qui lui est passé.) Alors que le Word d’origine. L’objet Body est un objet API. La toJSON méthode renvoie un objet JavaScript brut (typé en tant Word.Interfaces.BodyDataque ) qui contient des copies superficielles de toutes les propriétés enfants chargées à partir de l’objet d’origine.

toJSON(): Word.Interfaces.BodyData;

Retours

track()

Effectuer le suivi de l’objet pour l’ajustement automatique en fonction environnant des modifications dans le document. Cet appel est un raccourci pour context.trackedObjects.add(thisObject). Si vous utilisez cet objet sur des .sync appels et en dehors de l’exécution séquentielle d’un lot « .run », et que vous obtenez une erreur « InvalidObjectPath » lors de la définition d’une propriété ou de l’appel d’une méthode sur l’objet, vous devez ajouter l’objet à la collection d’objets suivie lors de la première création de l’objet. Si cet objet fait partie d’une collection, vous devez également suivre la collection parente.

track(): Word.Body;

Retours

untrack()

Publication mémoire associée à cet objet si elle a été précédemment suivie. Cet appel est abrégé pour context.trackedObjects.remove(thisObject). Vous rencontrez de nombreux objets suivies ralentit l’application hôte, donc n’oubliez pas de libérer les objets que l'on ajoute, une fois que vous avez terminé à les utiliser. Vous devez appeler context.sync() avant que la mise en production de la mémoire ne prenne effet.

untrack(): Word.Body;

Retours

Détails de l'événement

onCommentAdded

Notes

Cet API est fourni en tant qu’aperçu pour les développeurs et peut être modifié en fonction des commentaires que nous avons reçus. N’utilisez pas cet API dans un environnement de production.

Se produit lorsque de nouveaux commentaires sont ajoutés.

readonly onCommentAdded: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

Type d'événement

Remarques

[ Ensemble d’API : WordApi BETA (PRÉVERSION UNIQUEMENT) ]

onCommentChanged

Notes

Cet API est fourni en tant qu’aperçu pour les développeurs et peut être modifié en fonction des commentaires que nous avons reçus. N’utilisez pas cet API dans un environnement de production.

Se produit lorsqu’un commentaire ou sa réponse est modifié.

readonly onCommentChanged: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

Type d'événement

Remarques

[ Ensemble d’API : WordApi BETA (PRÉVERSION UNIQUEMENT) ]

onCommentDeleted

Notes

Cet API est fourni en tant qu’aperçu pour les développeurs et peut être modifié en fonction des commentaires que nous avons reçus. N’utilisez pas cet API dans un environnement de production.

Se produit lorsque les commentaires sont supprimés.

readonly onCommentDeleted: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

Type d'événement

Remarques

[ Ensemble d’API : WordApi BETA (PRÉVERSION UNIQUEMENT) ]

onCommentDeselected

Notes

Cet API est fourni en tant qu’aperçu pour les développeurs et peut être modifié en fonction des commentaires que nous avons reçus. N’utilisez pas cet API dans un environnement de production.

Se produit lorsqu’un commentaire est désélectionné.

readonly onCommentDeselected: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

Type d'événement

Remarques

[ Ensemble d’API : WordApi BETA (PRÉVERSION UNIQUEMENT) ]

onCommentSelected

Notes

Cet API est fourni en tant qu’aperçu pour les développeurs et peut être modifié en fonction des commentaires que nous avons reçus. N’utilisez pas cet API dans un environnement de production.

Se produit lorsqu’un commentaire est sélectionné.

readonly onCommentSelected: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

Type d'événement

Remarques

[ Ensemble d’API : WordApi BETA (PRÉVERSION UNIQUEMENT) ]