Word.Range class

Représente une zone contiguë dans un document.

Extends

Remarques

Jeu d’API : WordApi 1.1

Utilisateur

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Reads the text and checks whether the first paragraph range is empty.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    paragraphRange.load("text,isEmpty,style");
    await context.sync();
    console.log("First paragraph's properties:", { text: paragraphRange.text, isEmpty: paragraphRange.isEmpty, style: paragraphRange.style });
});

Propriétés

bold

Indique si la plage est mise en forme en gras.

boldBidirectional

Indique si la plage est mise en forme en gras dans un document de langue de droite à gauche.

bookmarks

Renvoie un BookmarkCollection objet qui représente tous les signets de la plage.

borders

Renvoie un BorderUniversalCollection objet qui représente toutes les bordures de la plage.

case

Spécifie une CharacterCase valeur qui représente la casse du texte dans la plage.

characterWidth

Spécifie la largeur de caractère de la plage.

combineCharacters

Indique si la plage contient des caractères combinés.

conflicts

Renvoie un ConflictCollection objet qui contient tout le Word. Objets de conflit dans la plage.

contentControls

Obtient la collection d’objets ContentControl de la plage.

context

Contexte de requête associé à l’objet. Cette opération connecte le processus du complément à celui de l’application hôte Office.

disableCharacterSpaceGrid

Indique si Microsoft Word ignore le nombre de caractères par ligne pour l’objet correspondantRange.

editors

Renvoie un EditorCollection objet qui représente tous les utilisateurs autorisés à modifier la plage lorsque le document est en mode protégé (lecture seule).

emphasisMark

Indique le trait d’accentuation d’un caractère ou d’une chaîne de caractères désignée.

end

Spécifie la position du caractère de fin de la plage.

endnotes

Obtient la collection des notes de fin dans la plage.

fields

Obtient la collection d’objets Field de la plage.

fitTextWidth

Spécifie la largeur (dans les unités de mesure actuelles) dans laquelle Microsoft Word ajuste le texte dans la sélection ou la plage actuelle.

font

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

footnotes

Obtient la collection des notes de bas de page dans la plage.

frames

Obtient un FrameCollection objet qui représente toutes les images de la plage.

grammarChecked

Indique si une case activée grammaticale a été exécutée sur la plage ou le document.

hasNoProofing

Spécifie le status de vérification (vérification de l’orthographe et de la grammaire) de la plage.

highlightColorIndex

Spécifie la couleur de surbrillance de la plage.

horizontalInVertical

Spécifie la mise en forme d’un texte horizontal défini dans un texte vertical.

hyperlink

Obtient le premier lien hypertexte de la plage ou définit un lien hypertexte sur la plage. Tous les liens hypertexte de la plage sont supprimés lorsque vous définissez un nouveau lien hypertexte sur celle-ci. Utilisez un « # » pour séparer la partie adresse de la partie emplacement facultative.

hyperlinks

Renvoie un HyperlinkCollection objet qui représente tous les liens hypertexte dans la plage.

id

Spécifie l’ID de la plage.

inlinePictures

Obtient la collection d’objets InlinePicture de la plage.

isEmpty

Vérifie si la longueur de la plage est zéro.

isEndOfRowMark

Indique si la plage est réduite et se trouve à la fin de la ligne d’un tableau.

isTextVisibleOnScreen

Détermine si le texte de la plage est visible à l’écran.

italic

Indique si la police ou la plage est mise en forme en italique.

italicBidirectional

Indique si la police ou la plage est mise en forme en italique (langues de droite à gauche).

kana

Indique si la plage du texte japonais est hiragana ou katakana.

languageDetected

Indique si Microsoft Word a détecté la langue du texte dans la plage.

languageId

Spécifie une LanguageId valeur qui représente la langue de la plage.

languageIdFarEast

Spécifie une langue d’Asie de l’Est pour la plage.

languageIdOther

Spécifie une langue pour la plage qui n’est pas classée comme langue d’Asie de l’Est.

listFormat

Renvoie un ListFormat objet qui représente toutes les caractéristiques de mise en forme de liste de la plage.

lists

Obtient la collection d’objets List de la plage.

pages

Obtient la collection de pages de la plage.

paragraphs

Obtient la collection d’objets Paragraph de la plage.

parentBody

Obtient le corps parent de la plage.

parentContentControl

Obtient le contrôle de contenu actuellement pris en charge qui contient la plage. Génère une ItemNotFound erreur s’il n’existe pas de contrôle de contenu parent.

parentContentControlOrNullObject

Obtient le contrôle de contenu actuellement pris en charge qui contient la plage. S’il n’existe pas de contrôle de contenu parent, cette méthode renvoie un objet dont la isNullObject propriété est définie sur true. Pour plus d’informations, consultez * Méthodes et propriétés d’OrNullObject.

parentTable

Obtient le tableau qui contient la plage. Génère une ItemNotFound erreur si elle n’est pas contenue dans une table.

parentTableCell

Obtient la cellule de tableau qui contient la plage. Génère une ItemNotFound erreur si elle n’est pas contenue dans une cellule de tableau.

parentTableCellOrNullObject

Obtient la cellule de tableau qui contient la plage. S’il n’est pas contenu dans une cellule de tableau, cette méthode renvoie un objet avec sa isNullObject propriété définie sur true. Pour plus d’informations, consultez * Méthodes et propriétés d’OrNullObject.

parentTableOrNullObject

Obtient le tableau qui contient la plage. S’il n’est pas contenu dans une table, cette méthode renvoie un objet avec sa isNullObject propriété définie sur true. Pour plus d’informations, consultez * Méthodes et propriétés d’OrNullObject.

revisions

Obtient la collection de révisions qui représente les modifications suivies dans la plage.

sections

Obtient la collection de sections de la plage.

shading

Renvoie un ShadingUniversal objet qui fait référence à la mise en forme d’ombrage de la plage.

shapes

Obtient la collection d’objets Shape ancrés dans la plage, y compris les formes incorporées et flottantes. Actuellement, seules les formes suivantes sont prises en charge : zones de texte, formes géométriques, groupes, images et canevas.

showAll

Indique si tous les caractères non imprimables (par exemple, texte masqué, marques de tabulation, marques d’espace et marques de paragraphe) sont affichés.

spellingChecked

Indique si l’orthographe a été vérifiée dans toute la plage ou le document.

start

Spécifie la position du caractère de départ de la plage.

storyLength

Obtient le nombre de caractères dans l’histoire qui contient la plage.

storyType

Obtient le type d’histoire de la plage.

style

Spécifie le nom du style de la plage. 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 du style intégré de la plage. 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 ».

tableColumns

Obtient un TableColumnCollection objet qui représente toutes les colonnes de la table.

tables

Obtient la collection d’objets Table de la plage.

text

Obtient le texte de la plage.

twoLinesInOne

Indique si Microsoft Word définit deux lignes de texte en une seule ligne et spécifie les caractères qui entourent le texte, le cas échéant.

underline

Spécifie le type de soulignement appliqué à la plage.

Méthodes

clear()

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

compareLocationWith(range)

Compare l’emplacement de la plage à celui d’une autre plage.

delete()

Supprime la plage et son contenu du document.

detectLanguage()

Analyse le texte de plage pour déterminer la langue dans laquelle il est écrit.

expandTo(range)

Renvoie une nouvelle plage qui s’étend dans les deux directions à partir de cette plage pour couvrir une autre plage. Cette plage n’est pas modifiée. Génère une ItemNotFound erreur si les deux plages n’ont pas d’union.

expandToOrNullObject(range)

Renvoie une nouvelle plage qui s’étend dans les deux directions à partir de cette plage pour couvrir une autre plage. Cette plage n’est pas modifiée. Si les deux plages n’ont pas d’union, cette méthode renvoie un objet dont la isNullObject propriété est définie sur true. Pour plus d’informations, consultez * Méthodes et propriétés d’OrNullObject.

getBookmarks(includeHidden, includeAdjacent)

Obtient les noms, tous les signets dans ou chevauchant la plage. Un signet est masqué si son nom commence par le caractère de soulignement.

getComments()

Obtient les commentaires associés à la plage.

getContentControls(options)

Obtient les contrôles de contenu actuellement pris en charge dans la plage.

getHtml()

Obtient une représentation HTML de l’objet Range . Dans une page web ou une visionneuse HTML, la mise en forme correspond étroitement, mais pas exactement, à la mise en forme du document. Cette méthode ne renvoie 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 Range.getOoxml() et convertissez le XML renvoyé en HTML.

getHyperlinkRanges()

Obtient les plages enfants d’un lien hypertexte au sein de la plage.

getNextTextRange(endingMarks, trimSpacing)

Obtient la plage de texte suivante à l’aide de signes de ponctuation et d’autres signes de fin. Génère une ItemNotFound erreur si cette plage de texte est la dernière.

getNextTextRangeOrNullObject(endingMarks, trimSpacing)

Obtient la plage de texte suivante à l’aide de signes de ponctuation et d’autres signes de fin. Si cette plage de texte est la dernière, cette méthode renvoie un objet dont la isNullObject propriété est définie sur true. Pour plus d’informations, consultez * Méthodes et propriétés d’OrNullObject.

getOoxml()

Obtient la représentation OOXML de l’objet Range .

getRange(rangeLocation)

Clone l’objet Range ou obtient le point de début ou de fin de la plage en tant que nouvelle plage.

getReviewedText(changeTrackingVersion)

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

getReviewedText(changeTrackingVersion)

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

getTextRanges(endingMarks, trimSpacing)

Obtient les plages enfants de texte dans la plage à l’aide de signes de ponctuation et d’autres signes de fin.

getTrackedChanges()

Obtient la collection des TrackedChange objets de la plage.

highlight()

Met en surbrillance la plage temporairement sans modifier le contenu du document. Pour mettre en surbrillance le texte de façon permanente, définissez la valeur de font.highlightColorla plage.

insertBookmark(name)

Insère un signet sur la plage. Si un signet du même nom existe quelque part, il est supprimé en premier.

insertBreak(breakType, insertLocation)

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

insertCanvas(insertShapeOptions)

Insère une zone de dessin flottante devant le texte avec son ancrage au début de la plage.

insertComment(commentText)

Insérez un commentaire sur la plage.

insertContentControl(contentControlType)

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

insertEndnote(insertText)

Insère une note de fin. La référence de note de fin est placée après la plage.

insertField(insertLocation, fieldType, text, removeFormatting)

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

insertField(insertLocation, fieldType, text, removeFormatting)

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

insertFileFromBase64(base64File, insertLocation)

Insère un document à l’emplacement spécifié. La taille maximale du document inséré est de 4 Mo.

insertFootnote(insertText)

insère une note de bas de page. La référence de note de bas de page est placée après la plage.

insertGeometricShape(geometricShapeType, insertShapeOptions)

Insère une forme géométrique devant le texte avec son ancrage au début de la plage.

insertGeometricShape(geometricShapeType, insertShapeOptions)

Insère une forme géométrique devant le texte avec son ancrage au début de la plage.

insertHtml(html, insertLocation)

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

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Insère une image à 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é.

insertPictureFromBase64(base64EncodedImage, insertShapeOptions)

Insère une image flottante devant le texte avec son ancrage au début de la plage.

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 à l’emplacement spécifié.

insertTextBox(text, insertShapeOptions)

Insère une zone de texte flottante devant le texte avec son ancrage au début de la plage.

intersectWith(range)

Retourne une nouvelle plage en tant qu’intersection de cette plage avec une autre. Cette plage n’est pas modifiée. Génère une ItemNotFound erreur si les deux plages ne sont pas superposées ou adjacentes.

intersectWithOrNullObject(range)

Retourne une nouvelle plage en tant qu’intersection de cette plage avec une autre. Cette plage n’est pas modifiée. Si les deux plages ne sont pas superposées ou adjacentes, cette méthode renvoie un objet dont la isNullObject propriété est définie sur true. Pour plus d’informations, consultez * Méthodes et propriétés d’OrNullObject.

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.

removeHighlight()

Supprime la surbrillance ajoutée par la méthode, le highlight cas échéant.

search(searchText, searchOptions)

Effectue une recherche avec les options de recherche spécifiées sur l’étendue de l’objet Range . Les résultats de la recherche sont une collection d’objets Range .

select(selectionMode)

Sélectionne la plage et y accède via l’interface utilisateur de Word.

select(selectionMode)

Sélectionne la plage 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 transmettre soit un objet ordinaire avec les propriétés appropriées, soit 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.

split(delimiters, multiParagraphs, trimDelimiters, trimSpacing)

Divise la plage en plages enfants à l’aide de délimiteurs.

toJSON()

Remplace la méthode JavaScript toJSON() afin de fournir une sortie plus utile lorsqu’un objet API est passé à JSON.stringify(). (JSON.stringify, à son tour, appelle la toJSON méthode de l’objet qui lui est passé.) Alors que l’objet d’origine Word.Range est un objet API, la toJSON méthode renvoie un objet JavaScript simple (typé ) Word.Interfaces.RangeDataqui 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 entre 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 suivis lors de la création initiale 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 l’abréviation de 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 libération de mémoire 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é.

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é

bold

Indique si la plage est mise en forme en gras.

readonly bold: boolean;

Valeur de propriété

boolean

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/character-formatting-and-case-desktop.yaml

// Reads character formatting on the first paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.load("text,bold,italic,boldBidirectional,italicBidirectional,case,highlightColorIndex");
    await context.sync();
    console.log("First paragraph's formatting:", {
        text: paragraphRange.text,
        bold: paragraphRange.bold,
        italic: paragraphRange.italic,
        boldBidirectional: paragraphRange.boldBidirectional,
        italicBidirectional: paragraphRange.italicBidirectional,
        case: paragraphRange.case,
        highlightColorIndex: paragraphRange.highlightColorIndex
    });
});

boldBidirectional

Indique si la plage est mise en forme en gras dans un document de langue de droite à gauche.

readonly boldBidirectional: boolean;

Valeur de propriété

boolean

Remarques

Jeu d’API : WordApiDesktop 1.4

bookmarks

Renvoie un BookmarkCollection objet qui représente tous les signets de la plage.

readonly bookmarks: Word.BookmarkCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/manage-range-bookmarks.yaml

// Read bookmark properties and the text enclosed by each bookmark.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const bookmarks: Word.BookmarkCollection = paragraphRange.bookmarks;
    bookmarks.load("items/name,items/start,items/end,items/isEmpty,items/isColumn,items/storyType,items/range/text");
    await context.sync();
    console.log(`Bookmarks found: ${bookmarks.items.length}`);
    bookmarks.items.forEach((bookmark: Word.Bookmark) => {
        console.log("Bookmark details:", {
            name: bookmark.name,
            start: bookmark.start,
            end: bookmark.end,
            isEmpty: bookmark.isEmpty,
            isColumn: bookmark.isColumn,
            storyType: bookmark.storyType,
            text: bookmark.range.text
        });
    });
});

borders

Renvoie un BorderUniversalCollection objet qui représente toutes les bordures de la plage.

readonly borders: Word.BorderUniversalCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-layout-desktop.yaml

// Reads the border formatting of the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const borders: Word.BorderUniversalCollection = paragraphRange.borders;
    borders.load("items/color,items/lineStyle,items/lineWidth,items/isVisible");
    await context.sync();
    console.log("First paragraph's border formatting:");
    borders.items.forEach((border: Word.BorderUniversal) => {
        console.log({ color: border.color, lineStyle: border.lineStyle, lineWidth: border.lineWidth, isVisible: border.isVisible });
    });
});

case

Spécifie une CharacterCase valeur qui représente la casse du texte dans la plage.

case: Word.CharacterCase | "Next" | "Lower" | "Upper" | "TitleWord" | "TitleSentence" | "Toggle" | "HalfWidth" | "FullWidth" | "Katakana" | "Hiragana";

Valeur de propriété

Word.CharacterCase | "Next" | "Lower" | "Upper" | "TitleWord" | "TitleSentence" | "Toggle" | "HalfWidth" | "FullWidth" | "Katakana" | "Hiragana"

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/character-formatting-and-case-desktop.yaml

// Converts the first paragraph's text to uppercase.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const characterCase: Word.CharacterCase = Word.CharacterCase.upper;
    paragraphRange.case = characterCase;
    await context.sync();
    console.log("Converted the first paragraph's text to uppercase.");
});

characterWidth

Spécifie la largeur de caractère de la plage.

characterWidth: Word.CharacterWidth | "Half" | "Full";

Valeur de propriété

Word.CharacterWidth | "Half" | "Full"

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml

// Converts the first paragraph's Latin characters and digits to full width.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const characterWidth: Word.CharacterWidth = Word.CharacterWidth.full;
    paragraphRange.characterWidth = characterWidth;
    await context.sync();
    console.log("Converted the first paragraph's Latin characters and digits to full width.");
});

combineCharacters

Indique si la plage contient des caractères combinés.

combineCharacters: boolean;

Valeur de propriété

boolean

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml

// Combines the first paragraph's short group of characters.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.combineCharacters = true;
    await context.sync();
    console.log("Enabled combined characters on the first paragraph. Get layout settings to inspect the flag.");
});

conflicts

Renvoie un ConflictCollection objet qui contient tout le Word. Objets de conflit dans la plage.

readonly conflicts: Word.ConflictCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/05-coauthoring/manage-coauthoring-conflicts.yaml

// Gets coauthoring conflicts associated with the selected range.
await Word.run(async (context) => {
    const selectedRange: Word.Range = context.document.getSelection();
    const conflicts: Word.ConflictCollection = selectedRange.conflicts;
    conflicts.load("items/type");
    await context.sync();
    console.log(`Conflicts in the selection: ${conflicts.items.length}`);
    conflicts.items.forEach((conflict: Word.Conflict) => console.log(`Conflict type: ${conflict.type}`));
});

contentControls

Obtient la collection d’objets ContentControl de la plage.

readonly contentControls: Word.ContentControlCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApi 1.1

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Gets the content controls contained in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const contentControls: Word.ContentControlCollection = bodyRange.contentControls;
    contentControls.load("items/tag,items/title,items/text");
    await context.sync();
    console.log(`Content controls found: ${contentControls.items.length}`);
    contentControls.items.forEach((control: Word.ContentControl) => {
        console.log({ tag: control.tag, title: control.title, text: control.text });
    });
});

context

Contexte de requête associé à l’objet. Cette opération connecte le processus du complément à celui de l’application hôte Office.

context: RequestContext;

Valeur de propriété

disableCharacterSpaceGrid

Indique si Microsoft Word ignore le nombre de caractères par ligne pour l’objet correspondantRange.

readonly disableCharacterSpaceGrid: boolean;

Valeur de propriété

boolean

Remarques

Jeu d’API : WordApiDesktop 1.4

editors

Renvoie un EditorCollection objet qui représente tous les utilisateurs autorisés à modifier la plage lorsque le document est en mode protégé (lecture seule).

readonly editors: Word.EditorCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/manage-range-editing-permissions-desktop.yaml

// Reads editing-permission entries for the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const editors: Word.EditorCollection = paragraphRange.editors;
    const editorCount: OfficeExtension.ClientResult<number> = editors.getCount();
    await context.sync();
    const editorEntries: Word.Editor[] = [];
    for (let index = 0; index < editorCount.value; index++) {
        const editor: Word.Editor = editors.getItemAt(index);
        editor.load("name,id");
        editorEntries.push(editor);
    }
    await context.sync();
    console.log(`Editing-permission entries: ${editorCount.value}`);
    editorEntries.forEach((editor: Word.Editor) => console.log({ name: editor.name, id: editor.id }));
});

emphasisMark

Indique le trait d’accentuation d’un caractère ou d’une chaîne de caractères désignée.

readonly emphasisMark: Word.EmphasisMark | "None" | "OverSolidCircle" | "OverComma" | "OverWhiteCircle" | "UnderSolidCircle";

Valeur de propriété

Word.EmphasisMark | "None" | "OverSolidCircle" | "OverComma" | "OverWhiteCircle" | "UnderSolidCircle"

Remarques

Jeu d’API : WordApiDesktop 1.4

end

Spécifie la position du caractère de fin de la plage.

end: number;

Valeur de propriété

number

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-and-adjust-range-boundaries-desktop.yaml

// Selects the first paragraph's text except its last character.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.load("start,end");
    await context.sync();
    if (paragraphRange.start === paragraphRange.end) {
        console.warn("The paragraph is empty. Run Set up again.");
        return;
    }
    paragraphRange.end = paragraphRange.end - 1;
    paragraphRange.select();
    await context.sync();
    console.log("Selected the range with its ending position reduced by one character.");
});

endnotes

Obtient la collection des notes de fin dans la plage.

readonly endnotes: Word.NoteItemCollection;

Valeur de propriété

Remarques

Jeu 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 text of every endnote in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const endnotes: Word.NoteItemCollection = bodyRange.endnotes;
    endnotes.load("items/body/text");
    await context.sync();
    console.log(`Endnotes found: ${endnotes.items.length}`);
    endnotes.items.forEach((endnote: Word.NoteItem) => console.log(endnote.body.text));
});

fields

Obtient la collection d’objets Field de la plage.

readonly fields: Word.FieldCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApi 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Gets field codes and displayed results in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const fields: Word.FieldCollection = bodyRange.fields;
    fields.load("items/code,items/result/text");
    await context.sync();
    console.log(`Fields found: ${fields.items.length}`);
    fields.items.forEach((field: Word.Field) => console.log({ code: field.code, text: field.result.text }));
});

fitTextWidth

Spécifie la largeur (dans les unités de mesure actuelles) dans laquelle Microsoft Word ajuste le texte dans la sélection ou la plage actuelle.

fitTextWidth: number;

Valeur de propriété

number

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml

// Fits the first paragraph's text into a specified width.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.fitTextWidth = 100;
    await context.sync();
    console.log("Fitted the first paragraph's text into 100 current measurement units.");
});

font

Obtient le format de texte de la plage. Utilisez cette propriété 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

Jeu 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) => {
  // Insert the sentence, then adjust the formatting.
  // Note that replace affects the calling object, in this case the entire document body.
  // A similar method can also be used at the range level.
  const sentence: Word.Range = context.document.body.insertText(
    "This is some formatted text!",
    "Replace"
  );
  sentence.font.set({
    name: "Courier New",
    bold: true,
    size: 18
  });

  await context.sync();
});

footnotes

Obtient la collection des notes de bas de page dans la plage.

readonly footnotes: Word.NoteItemCollection;

Valeur de propriété

Remarques

Jeu 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 selected document range.
await Word.run(async (context) => {
  const footnotes: Word.NoteItemCollection = context.document.getSelection().footnotes;
  footnotes.load("length");
  await context.sync();

  console.log(`Number of footnotes in the selected range: ${footnotes.items.length}`);
});

frames

Obtient un FrameCollection objet qui représente toutes les images de la plage.

readonly frames: Word.FrameCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApiDesktop 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-layout-desktop.yaml

// Reads the text and dimensions of frames in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const frames: Word.FrameCollection = bodyRange.frames;
    frames.load("items/width,items/height,items/range/text");
    await context.sync();
    console.log(`Frames found: ${frames.items.length}`);
    frames.items.forEach((frame: Word.Frame) => {
        console.log({ width: frame.width, height: frame.height, text: frame.range.text });
    });
});

grammarChecked

Indique si une case activée grammaticale a été exécutée sur la plage ou le document.

grammarChecked: boolean;

Valeur de propriété

boolean

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml

// Marks the first paragraph as needing another grammar check.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.grammarChecked = false;
    await context.sync();
    console.log("Reset the English paragraph's grammar-checked flag. Get language and proofing settings to inspect it.");
});

hasNoProofing

Spécifie le status de vérification (vérification de l’orthographe et de la grammaire) de la plage.

hasNoProofing: boolean;

Valeur de propriété

boolean

Remarques

Jeu d’API : WordApiDesktop 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml

// Disables spelling and grammar checking for the first paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.hasNoProofing = true;
    await context.sync();
    console.log("Disabled spelling and grammar checking for the English paragraph. Get language and proofing settings to verify it.");
});

highlightColorIndex

Spécifie la couleur de surbrillance de la plage.

readonly highlightColorIndex: Word.ColorIndex | "Auto" | "Black" | "Blue" | "Turquoise" | "BrightGreen" | "Pink" | "Red" | "Yellow" | "White" | "DarkBlue" | "Teal" | "Green" | "Violet" | "DarkRed" | "DarkYellow" | "Gray50" | "Gray25" | "ClassicRed" | "ClassicBlue" | "ByAuthor";

Valeur de propriété

Word.ColorIndex | "Auto" | "Black" | "Blue" | "Turquoise" | "BrightGreen" | "Pink" | "Red" | "Yellow" | "White" | "DarkBlue" | "Teal" | "Green" | "Violet" | "DarkRed" | "DarkYellow" | "Gray50" | "Gray25" | "ClassicRed" | "ClassicBlue" | "ByAuthor"

Remarques

Jeu d’API : WordApiDesktop 1.4

horizontalInVertical

Spécifie la mise en forme d’un texte horizontal défini dans un texte vertical.

horizontalInVertical: Word.HorizontalInVerticalType | "None" | "FitInLine" | "ResizeLine";

Valeur de propriété

Word.HorizontalInVerticalType | "None" | "FitInLine" | "ResizeLine"

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml

// Keeps the first paragraph's characters horizontal within vertical text.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const horizontalLayout: Word.HorizontalInVerticalType = Word.HorizontalInVerticalType.fitInLine;
    paragraphRange.horizontalInVertical = horizontalLayout;
    await context.sync();
    console.log("Enabled horizontal-in-vertical layout on the first paragraph. Get layout settings to verify it.");
});

Obtient le premier lien hypertexte de la plage ou définit un lien hypertexte sur la plage. Tous les liens hypertexte de la plage sont supprimés lorsque vous définissez un nouveau lien hypertexte sur celle-ci. Utilisez un « # » pour séparer la partie adresse de la partie emplacement facultative.

hyperlink: string;

Valeur de propriété

string

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Links the first paragraph's text to the Word add-in documentation.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.hyperlink = "https://learn.microsoft.com/office/dev/add-ins/word/";
    await context.sync();
    console.log("Linked the summary text to the Word add-in documentation.");
});

Renvoie un HyperlinkCollection objet qui représente tous les liens hypertexte dans la plage.

readonly hyperlinks: Word.HyperlinkCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApiDesktop 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-layout-desktop.yaml

// Reads hyperlink objects and their destinations in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const hyperlinks: Word.HyperlinkCollection = bodyRange.hyperlinks;
    hyperlinks.load("items/address,items/range/text");
    await context.sync();
    console.log(`Hyperlinks found: ${hyperlinks.items.length}`);
    hyperlinks.items.forEach((hyperlink: Word.Hyperlink) => {
        console.log({ address: hyperlink.address, text: hyperlink.range.text });
    });
});

id

Spécifie l’ID de la plage.

id: string;

Valeur de propriété

string

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-and-adjust-range-boundaries-desktop.yaml

// Reads the range's character positions and the story containing it.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.load("id,start,end,storyLength,storyType,isEndOfRowMark,isTextVisibleOnScreen");
    await context.sync();
    console.log("First paragraph's position and story:", {
        id: paragraphRange.id,
        start: paragraphRange.start,
        end: paragraphRange.end,
        storyLength: paragraphRange.storyLength,
        storyType: paragraphRange.storyType,
        isEndOfRowMark: paragraphRange.isEndOfRowMark,
        isTextVisibleOnScreen: paragraphRange.isTextVisibleOnScreen
    });
});

inlinePictures

Obtient la collection d’objets InlinePicture de la plage.

readonly inlinePictures: Word.InlinePictureCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApi 1.2

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Reads the dimensions of inline pictures in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const pictures: Word.InlinePictureCollection = bodyRange.inlinePictures;
    pictures.load("items/width,items/height");
    await context.sync();
    console.log(`Inline pictures found: ${pictures.items.length}`);
    pictures.items.forEach((picture: Word.InlinePicture) => console.log({ width: picture.width, height: picture.height }));
});

isEmpty

Vérifie si la longueur de la plage est zéro.

readonly isEmpty: boolean;

Valeur de propriété

boolean

Remarques

Jeu d’API : WordApi 1.3

isEndOfRowMark

Indique si la plage est réduite et se trouve à la fin de la ligne d’un tableau.

readonly isEndOfRowMark: boolean;

Valeur de propriété

boolean

Remarques

Jeu d’API : WordApiDesktop 1.4

isTextVisibleOnScreen

Détermine si le texte de la plage est visible à l’écran.

readonly isTextVisibleOnScreen: boolean;

Valeur de propriété

boolean

Remarques

Jeu d’API : WordApiDesktop 1.4

italic

Indique si la police ou la plage est mise en forme en italique.

readonly italic: boolean;

Valeur de propriété

boolean

Remarques

Jeu d’API : WordApiDesktop 1.4

italicBidirectional

Indique si la police ou la plage est mise en forme en italique (langues de droite à gauche).

readonly italicBidirectional: boolean;

Valeur de propriété

boolean

Remarques

Jeu d’API : WordApiDesktop 1.4

kana

Indique si la plage du texte japonais est hiragana ou katakana.

kana: Word.Kana | "Katakana" | "Hiragana";

Valeur de propriété

Word.Kana | "Katakana" | "Hiragana"

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/convert-japanese-kana-desktop.yaml

// Converts the sample paragraph's Japanese katakana text to hiragana.
await Word.run(async (context) => {
    const japaneseRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const kana: Word.Kana = Word.Kana.hiragana;
    japaneseRange.kana = kana;
    await context.sync();
    console.log("Converted the Japanese paragraph's text to hiragana.");
});

languageDetected

Indique si Microsoft Word a détecté la langue du texte dans la plage.

languageDetected: boolean;

Valeur de propriété

boolean

Remarques

Jeu d’API : WordApiDesktop 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml

// Marks the first paragraph's language as not yet detected.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.languageDetected = false;
    await context.sync();
    console.log("Reset the English paragraph's language-detected flag. Get language and proofing settings to inspect it.");
});

languageId

Spécifie une LanguageId valeur qui représente la langue de la plage.

languageId: Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu";

Valeur de propriété

Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu"

Remarques

Jeu d’API : WordApiDesktop 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml

// Sets the first paragraph's proofing language to US English.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const language: Word.LanguageId = Word.LanguageId.englishUS;
    paragraphRange.languageId = language;
    await context.sync();
    console.log("Set the English paragraph's proofing language to US English.");
});

languageIdFarEast

Spécifie une langue d’Asie de l’Est pour la plage.

languageIdFarEast: Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu";

Valeur de propriété

Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu"

Remarques

Jeu d’API : WordApiDesktop 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml

// Sets the Japanese paragraph's East Asian language.
await Word.run(async (context) => {
    const japaneseRange: Word.Range = context.document.body.paragraphs.getLast().getRange(Word.RangeLocation.content);
    const language: Word.LanguageId = Word.LanguageId.japanese;
    japaneseRange.languageIdFarEast = language;
    await context.sync();
    console.log("Set the Japanese paragraph's East Asian language to Japanese.");
});

languageIdOther

Spécifie une langue pour la plage qui n’est pas classée comme langue d’Asie de l’Est.

languageIdOther: Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu";

Valeur de propriété

Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu"

Remarques

Jeu d’API : WordApiDesktop 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml

// Sets the first paragraph's non-East-Asian language to US English.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const language: Word.LanguageId = Word.LanguageId.englishUS;
    paragraphRange.languageIdOther = language;
    await context.sync();
    console.log("Set the English paragraph's non-East-Asian language to US English.");
});

listFormat

Renvoie un ListFormat objet qui représente toutes les caractéristiques de mise en forme de liste de la plage.

readonly listFormat: Word.ListFormat;

Valeur de propriété

Remarques

Jeu d’API : WordApiDesktop 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/20-lists/format-list-range.yaml

// Gets the range covering the entire body and reads list formatting properties.
await Word.run(async (context) => {
  const bodyRange: Word.Range = context.document.body.getRange();
  const listFormat: Word.ListFormat = bodyRange.listFormat;
  listFormat.load("isSingleList, listType, listLevelNumber, listString, listValue");
  await context.sync();

  console.log("List format info for the body range:");
  console.log(`- Is single list: ${listFormat.isSingleList}`);
  console.log(`- List type: ${listFormat.listType}`);
  console.log(`- List level number (first paragraph): ${listFormat.listLevelNumber}`);
  console.log(`- List string (first paragraph): "${listFormat.listString}"`);
  console.log(`- List value (first paragraph): ${listFormat.listValue}`);
});

lists

Obtient la collection d’objets List de la plage.

readonly lists: Word.ListCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Reads the identifiers of lists in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const lists: Word.ListCollection = bodyRange.lists;
    lists.load("items/id");
    await context.sync();
    console.log(`Lists found: ${lists.items.length}`);
    lists.items.forEach((list: Word.List) => console.log(`List ID: ${list.id}`));
});

pages

Obtient la collection de pages de la plage.

readonly pages: Word.PageCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApiDesktop 1.2

Exemples

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

// Reads the index and text of each page intersecting the selection.
await Word.run(async (context) => {
  const selectedRange: Word.Range = context.document.getSelection();
  const pages: Word.PageCollection = selectedRange.pages;
  pages.load("items/index");
  await context.sync();

  console.log(`Pages in the selection: ${pages.items.length}`);
  const pageRanges: Word.Range[] = [];
  pages.items.forEach((page: Word.Page) => {
    const pageRange: Word.Range = page.getRange(Word.RangeLocation.whole);
    pageRange.load("text");
    pageRanges.push(pageRange);
  });

  await context.sync();

  for (let i = 0; i < pages.items.length; i++) {
    console.log(`Page ${pages.items[i].index} text: ${pageRanges[i].text}`);
  }
});

paragraphs

Obtient la collection d’objets Paragraph de la plage.

readonly paragraphs: Word.ParagraphCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApi 1.1

Important : Pour les ensembles d’exigences 1.1 et 1.2, les paragraphes des tables entièrement contenues dans cette plage ne sont pas renvoyés. À partir de l’ensemble d’exigences 1.3, les paragraphes de ces tableaux sont également renvoyés.

Exemples

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

// Accepts the first annotation found in the selected paragraph.
await Word.run(async (context) => {
  const paragraph: Word.Paragraph = context.document.getSelection().paragraphs.getFirst();
  const annotations: Word.AnnotationCollection = paragraph.getAnnotations();
  annotations.load("id,state,critiqueAnnotation");

  await context.sync();

  for (let i = 0; i < annotations.items.length; i++) {
    const annotation: Word.Annotation = annotations.items[i];

    if (annotation.state === Word.AnnotationState.created) {
      console.log(`Accepting ID ${annotation.id}...`);
      annotation.critiqueAnnotation.accept();

      await context.sync();
      break;
    }
  }
});

parentBody

Obtient le corps parent de la plage.

readonly parentBody: Word.Body;

Valeur de propriété

Remarques

Jeu d’API : WordApi 1.3

Exemples

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

// Gets the section after the current selection when another section is expected.
await Word.run(async (context) => {
  const selection: Word.Range = context.document.getSelection();
  const selectedBody: Word.Body = selection.parentBody;
  const selectedSection: Word.Section = selectedBody.parentSection;
  const nextSection: Word.Section = selectedSection.getNext();
  const nextSectionBody: Word.Body = nextSection.body;
  nextSectionBody.load("text");

  await context.sync();

  console.log(`Next section text: ${nextSectionBody.text}`);
});

parentContentControl

Obtient le contrôle de contenu actuellement pris en charge qui contient la plage. 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

Jeu d’API : WordApi 1.1

Exemples

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

// Toggles the isChecked property of the first checkbox content control found in the selection.
await Word.run(async (context) => {
  const selectedRange: Word.Range = context.document.getSelection();
  let selectedContentControl = selectedRange
    .getContentControls({
      types: [Word.ContentControlType.checkBox]
    })
    .getFirstOrNullObject();
  selectedContentControl.load("id,checkboxContentControl/isChecked");

  await context.sync();

  if (selectedContentControl.isNullObject) {
    const parentContentControl: Word.ContentControl = selectedRange.parentContentControl;
    parentContentControl.load("id,type,checkboxContentControl/isChecked");
    await context.sync();

    if (parentContentControl.isNullObject || parentContentControl.type !== Word.ContentControlType.checkBox) {
      console.warn("No checkbox content control is currently selected.");
      return;
    } else {
      selectedContentControl = parentContentControl;
    }
  }

  const isCheckedBefore = selectedContentControl.checkboxContentControl.isChecked;
  console.log("isChecked state before:", `id: ${selectedContentControl.id} ... isChecked: ${isCheckedBefore}`);
  selectedContentControl.checkboxContentControl.isChecked = !isCheckedBefore;
  selectedContentControl.load("id,checkboxContentControl/isChecked");
  await context.sync();

  console.log(
    "isChecked state after:",
    `id: ${selectedContentControl.id} ... isChecked: ${selectedContentControl.checkboxContentControl.isChecked}`
  );
});

parentContentControlOrNullObject

Obtient le contrôle de contenu actuellement pris en charge qui contient la plage. S’il n’existe pas de contrôle de contenu parent, cette méthode renvoie un objet dont la isNullObject propriété est définie sur true. Pour plus d’informations, consultez * Méthodes et propriétés d’OrNullObject.

readonly parentContentControlOrNullObject: Word.ContentControl;

Valeur de propriété

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-date-picker-content-control.yaml

// Deletes the first date picker content control found in the selection.
await Word.run(async (context) => {
  // First, look if the selection contains a date picker content control.
  const selectedRange: Word.Range = context.document.getSelection();
  let selectedContentControl = selectedRange
    .getContentControls({
      types: [Word.ContentControlType.datePicker]
    })
    .getFirstOrNullObject();
  selectedContentControl.load("id");

  await context.sync();

  // The selection doesn't contain a date picker, but the cursor might be inside one.
  // Check if the selection's parent content control is a date picker.
  if (selectedContentControl.isNullObject) {
    const parentContentControl: Word.ContentControl = selectedRange.parentContentControlOrNullObject;
    parentContentControl.load("id,type");
    await context.sync();

    if (parentContentControl.isNullObject || parentContentControl.type !== Word.ContentControlType.datePicker) {
      console.warn("Please select a date picker content control before selecting Delete.");
      return;
    }
    
    selectedContentControl = parentContentControl;
  }

  console.log(`About to delete date picker content control with ID: ${selectedContentControl.id}`);
  selectedContentControl.delete(false);
  await context.sync();

  console.log("Deleted date picker content control.");
});

parentTable

Obtient le tableau qui contient la plage. Génère une ItemNotFound erreur si elle n’est pas contenue dans une table.

readonly parentTable: Word.Table;

Valeur de propriété

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Reads the table containing the first table cell's range.
await Word.run(async (context) => {
    const cellRange: Word.Range = context.document.body.tables.getFirst().getCell(0, 0).body.getRange();
    const parentTable: Word.Table = cellRange.parentTable;
    parentTable.load("rowCount,values");
    await context.sync();
    console.log("Parent table:", { rowCount: parentTable.rowCount, values: parentTable.values });
});

parentTableCell

Obtient la cellule de tableau qui contient la plage. Génère une ItemNotFound erreur si elle n’est pas contenue dans une cellule de tableau.

readonly parentTableCell: Word.TableCell;

Valeur de propriété

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Reads the cell containing the first table cell's range.
await Word.run(async (context) => {
    const cellRange: Word.Range = context.document.body.tables.getFirst().getCell(0, 0).body.getRange();
    const parentCell: Word.TableCell = cellRange.parentTableCell;
    parentCell.load("rowIndex,cellIndex,value");
    await context.sync();
    console.log("Parent cell:", { rowIndex: parentCell.rowIndex, cellIndex: parentCell.cellIndex, value: parentCell.value });
});

parentTableCellOrNullObject

Obtient la cellule de tableau qui contient la plage. S’il n’est pas contenu dans une cellule de tableau, cette méthode renvoie un objet avec sa isNullObject propriété définie sur true. Pour plus d’informations, consultez * Méthodes et propriétés d’OrNullObject.

readonly parentTableCellOrNullObject: Word.TableCell;

Valeur de propriété

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Checks whether the first paragraph is inside a table cell.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const parentCell: Word.TableCell = paragraphRange.parentTableCellOrNullObject;
    parentCell.load("value");
    await context.sync();
    if (parentCell.isNullObject) {
        console.warn("The first paragraph is not inside a table cell.");
        return;
    }
    console.log(`Parent cell text: ${parentCell.value}`);
});

parentTableOrNullObject

Obtient le tableau qui contient la plage. S’il n’est pas contenu dans une table, cette méthode renvoie un objet avec sa isNullObject propriété définie sur true. Pour plus d’informations, consultez * Méthodes et propriétés d’OrNullObject.

readonly parentTableOrNullObject: Word.Table;

Valeur de propriété

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Checks whether the first paragraph is inside a table.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const parentTable: Word.Table = paragraphRange.parentTableOrNullObject;
    parentTable.load("rowCount");
    await context.sync();
    if (parentTable.isNullObject) {
        console.warn("The first paragraph is not inside a table.");
        return;
    }
    console.log(`Parent table rows: ${parentTable.rowCount}`);
});

revisions

Obtient la collection de révisions qui représente les modifications suivies dans la plage.

readonly revisions: Word.RevisionCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

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

// Reads revision metadata for the first paragraph on desktop Word.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const revisions: Word.RevisionCollection = paragraphRange.revisions;
    revisions.load("items/author,items/date,items/type,items/index,items/formatDescription");
    await context.sync();
    console.log(`Revisions in the first paragraph: ${revisions.items.length}`);
    revisions.items.forEach((revision: Word.Revision) => {
        console.log("Revision properties:", {
            author: revision.author,
            date: revision.date,
            type: revision.type,
            index: revision.index,
            formatDescription: revision.formatDescription,
        });
    });
});

sections

Obtient la collection de sections de la plage.

readonly sections: Word.SectionCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApiDesktop 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-layout-desktop.yaml

// Reads the text of sections intersecting the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const sections: Word.SectionCollection = bodyRange.sections;
    sections.load("items/body/text");
    await context.sync();
    console.log(`Sections found: ${sections.items.length}`);
    sections.items.forEach((section: Word.Section) => console.log(section.body.text));
});

shading

Renvoie un ShadingUniversal objet qui fait référence à la mise en forme d’ombrage de la plage.

readonly shading: Word.ShadingUniversal;

Valeur de propriété

Remarques

Jeu d’API : WordApiDesktop 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-layout-desktop.yaml

// Adds a pale blue background to the first paragraph's text.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const shading: Word.ShadingUniversal = paragraphRange.shading;
    shading.backgroundPatternColor = "#DDEBF7";
    await context.sync();
    console.log("Applied pale blue shading.");
});

shapes

Obtient la collection d’objets Shape ancrés dans la plage, y compris les formes incorporées et flottantes. Actuellement, seules les formes suivantes sont prises en charge : zones de texte, formes géométriques, groupes, images et canevas.

readonly shapes: Word.ShapeCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApiDesktop 1.2

Important : sachez qu’avec le temps, d’autres types de formes peuvent être pris en charge. Par conséquent, votre complément doit demander et gérer des types de formes spécifiques.

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-layout-desktop.yaml

// Reads shapes anchored within the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const shapes: Word.ShapeCollection = paragraphRange.shapes;
    shapes.load("items/name,items/type,items/width,items/height");
    await context.sync();
    console.log(`Shapes found: ${shapes.items.length}`);
    shapes.items.forEach((shape: Word.Shape) => {
        console.log({ name: shape.name, type: shape.type, width: shape.width, height: shape.height });
    });
});

showAll

Indique si tous les caractères non imprimables (par exemple, texte masqué, marques de tabulation, marques d’espace et marques de paragraphe) sont affichés.

showAll: boolean;

Valeur de propriété

boolean

Remarques

Jeu d’API : WordApiDesktop 1.4

spellingChecked

Indique si l’orthographe a été vérifiée dans toute la plage ou le document.

spellingChecked: boolean;

Valeur de propriété

boolean

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml

// Marks the first paragraph as needing another spelling check.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.spellingChecked = false;
    await context.sync();
    console.log("Reset the English paragraph's spelling-checked flag. Get language and proofing settings to inspect it.");
});

start

Spécifie la position du caractère de départ de la plage.

start: number;

Valeur de propriété

number

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-and-adjust-range-boundaries-desktop.yaml

// Selects the first paragraph's text except its first character.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.load("start,end");
    await context.sync();
    if (paragraphRange.start === paragraphRange.end) {
        console.warn("The paragraph is empty. Run Set up again.");
        return;
    }
    paragraphRange.start = paragraphRange.start + 1;
    paragraphRange.select();
    await context.sync();
    console.log("Selected the range with its starting position advanced by one character.");
});

storyLength

Obtient le nombre de caractères dans l’histoire qui contient la plage.

readonly storyLength: number;

Valeur de propriété

number

Remarques

Jeu d’API : WordApiDesktop 1.4

storyType

Obtient le type d’histoire de la plage.

readonly storyType: Word.StoryType | "MainText" | "Footnotes" | "Endnotes" | "Comments" | "TextFrame" | "EvenPagesHeader" | "PrimaryHeader" | "EvenPagesFooter" | "PrimaryFooter" | "FirstPageHeader" | "FirstPageFooter" | "FootnoteSeparator" | "FootnoteContinuationSeparator" | "FootnoteContinuationNotice" | "EndnoteSeparator" | "EndnoteContinuationSeparator" | "EndnoteContinuationNotice";

Valeur de propriété

Word.StoryType | "MainText" | "Footnotes" | "Endnotes" | "Comments" | "TextFrame" | "EvenPagesHeader" | "PrimaryHeader" | "EvenPagesFooter" | "PrimaryFooter" | "FirstPageHeader" | "FirstPageFooter" | "FootnoteSeparator" | "FootnoteContinuationSeparator" | "FootnoteContinuationNotice" | "EndnoteSeparator" | "EndnoteContinuationSeparator" | "EndnoteContinuationNotice"

Remarques

Jeu d’API : WordApiDesktop 1.4

style

Spécifie le nom du style de la plage. 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

Jeu d’API : WordApi 1.1

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Applies the sample's custom paragraph style to the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    paragraphRange.style = "RangeSampleStyle";
    await context.sync();
    console.log("Applied the sample's custom style.");
});

styleBuiltIn

Spécifie le nom du style intégré de la plage. 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

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/90-scenarios/doc-assembly.yaml

await Word.run(async (context) => {
    const header: Word.Range = context.document.body.insertText("This is a sample Heading 1 Title!!\n",
        "Start" /*this means at the beginning of the body */);
    header.styleBuiltIn = Word.BuiltInStyleName.heading1;

    await context.sync();
});

tableColumns

Obtient un TableColumnCollection objet qui représente toutes les colonnes de la table.

readonly tableColumns: Word.TableColumnCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApiDesktop 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/40-tables/manage-table-rows-columns-cells.yaml

// Gets properties of the first column in the sample table.
await Word.run(async (context) => {
  const firstTable: Word.Table = context.document.body.tables.getFirst();
  const tableRange: Word.Range = firstTable.getRange();
  const tableColumns: Word.TableColumnCollection = tableRange.tableColumns;
  tableColumns.load("items/columnIndex,items/isFirst,items/isLast,items/width");
  await context.sync();

  const firstColumn: Word.TableColumn = tableColumns.items[0];
  console.log(
    "First table column:",
    `- Index: ${firstColumn.columnIndex}`,
    `- Is first: ${firstColumn.isFirst}`,
    `- Is last: ${firstColumn.isLast}`,
    `- Width: ${firstColumn.width} points`
  );
});

tables

Obtient la collection d’objets Table de la plage.

readonly tables: Word.TableCollection;

Valeur de propriété

Remarques

Jeu d’API : WordApi 1.3

text

Obtient le texte de la plage.

readonly text: string;

Valeur de propriété

string

Remarques

Jeu d’API : WordApi 1.1

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/05-coauthoring/get-coauthoring-updates.yaml

// Gets the ranges affected by the most recent coauthoring updates merged into the document.
await Word.run(async (context) => {
  const updates: Word.CoauthoringUpdateCollection = context.document.coauthoring.updates;
  updates.load("items/range");
  await context.sync();

  if (updates.items.length === 0) {
    console.log("No recent coauthoring updates found.");
    return;
  }

  console.log(`Found ${updates.items.length} recent update(s).`);

  const ranges = updates.items.map((u) => u.range);
  ranges.forEach((r) => r.load("text"));
  await context.sync();

  ranges.forEach((range, i) => {
    console.log(`  Update ${i + 1}: "${range.text}"`);
  });
});

twoLinesInOne

Indique si Microsoft Word définit deux lignes de texte en une seule ligne et spécifie les caractères qui entourent le texte, le cas échéant.

twoLinesInOne: Word.TwoLinesInOneType | "None" | "NoBrackets" | "Parentheses" | "SquareBrackets" | "AngleBrackets" | "CurlyBrackets";

Valeur de propriété

Word.TwoLinesInOneType | "None" | "NoBrackets" | "Parentheses" | "SquareBrackets" | "AngleBrackets" | "CurlyBrackets"

Remarques

Jeu d’API : WordApiDesktop 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml

// Displays the first paragraph's text as two lines enclosed in parentheses.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const twoLineLayout: Word.TwoLinesInOneType = Word.TwoLinesInOneType.parentheses;
    paragraphRange.twoLinesInOne = twoLineLayout;
    await context.sync();
    console.log("Applied two-line text with parentheses to the first paragraph.");
});

underline

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.

Spécifie le type de soulignement appliqué à la plage.

readonly underline: Word.UnderlineType | "Mixed" | "None" | "Hidden" | "DotLine" | "Single" | "Word" | "Double" | "Thick" | "Dotted" | "DottedHeavy" | "DashLine" | "DashLineHeavy" | "DashLineLong" | "DashLineLongHeavy" | "DotDashLine" | "DotDashLineHeavy" | "TwoDotDashLine" | "TwoDotDashLineHeavy" | "Wave" | "WaveHeavy" | "WaveDouble";

Valeur de propriété

Word.UnderlineType | "Mixed" | "None" | "Hidden" | "DotLine" | "Single" | "Word" | "Double" | "Thick" | "Dotted" | "DottedHeavy" | "DashLine" | "DashLineHeavy" | "DashLineLong" | "DashLineLongHeavy" | "DotDashLine" | "DotDashLineHeavy" | "TwoDotDashLine" | "TwoDotDashLineHeavy" | "Wave" | "WaveHeavy" | "WaveDouble"

Remarques

Jeu d’API : WordApi BÊTA (PRÉVERSION UNIQUEMENT)

Exemples

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

// Reads the underline applied to the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.load("underline");
    await context.sync();
    const singleUnderline: Word.UnderlineType = Word.UnderlineType.single;
    console.log(`Underline type: ${paragraphRange.underline}`);
    console.log(`Has a single underline: ${paragraphRange.underline === singleUnderline}`);
});

Détails de la méthode

clear()

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

clear(): void;

Retours

void

Remarques

Jeu d’API : WordApi 1.1

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Removes the first paragraph's text while preserving the paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.clear();
    await context.sync();
    console.log("Cleared the summary text. The paragraph remains.");
});

compareLocationWith(range)

Compare l’emplacement de la plage à celui d’une autre plage.

compareLocationWith(range: Word.Range): OfficeExtension.ClientResult<Word.LocationRelation>;

Paramètres

range
Word.Range

Plage à comparer avec cette plage.

Retours

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml

// Compares the location of one paragraph in relation to another paragraph.
await Word.run(async (context) => {
  const paragraphs: Word.ParagraphCollection = context.document.body.paragraphs;
  paragraphs.load("items");

  await context.sync();

  const firstParagraphAsRange: Word.Range = paragraphs.items[0].getRange();
  const secondParagraphAsRange: Word.Range = paragraphs.items[1].getRange();

  const comparedLocation: OfficeExtension.ClientResult<Word.LocationRelation> =
    firstParagraphAsRange.compareLocationWith(secondParagraphAsRange);

  await context.sync();

  const locationValue: Word.LocationRelation = comparedLocation.value;
  console.log(`Location of the first paragraph in relation to the second paragraph: ${locationValue}`);
});

delete()

Supprime la plage et son contenu du document.

delete(): void;

Retours

void

Remarques

Jeu d’API : WordApi 1.1

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Deletes the first paragraph range, including its paragraph mark.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    paragraphRange.delete();
    await context.sync();
    console.log("Deleted the first paragraph range.");
});

detectLanguage()

Analyse le texte de plage pour déterminer la langue dans laquelle il est écrit.

detectLanguage(): OfficeExtension.ClientResult<boolean>;

Retours

Remarques

Jeu d’API : WordApiDesktop 1.3

expandTo(range)

Renvoie une nouvelle plage qui s’étend dans les deux directions à partir de cette plage pour couvrir une autre plage. Cette plage n’est pas modifiée. Génère une ItemNotFound erreur si les deux plages n’ont pas d’union.

expandTo(range: Word.Range): Word.Range;

Paramètres

range
Word.Range

Une autre gamme.

Retours

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml

// Gets the text spanning the first two paragraphs.
await Word.run(async (context) => {
    const firstRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const secondRange: Word.Range = context.document.body.paragraphs.getFirst().getNext().getRange();
    const expandedRange: Word.Range = firstRange.expandTo(secondRange);
    expandedRange.load("text");
    await context.sync();
    console.log(`Expanded text: ${expandedRange.text}`);
});

expandToOrNullObject(range)

Renvoie une nouvelle plage qui s’étend dans les deux directions à partir de cette plage pour couvrir une autre plage. Cette plage n’est pas modifiée. Si les deux plages n’ont pas d’union, cette méthode renvoie un objet dont la isNullObject propriété est définie sur true. Pour plus d’informations, consultez * Méthodes et propriétés d’OrNullObject.

expandToOrNullObject(range: Word.Range): Word.Range;

Paramètres

range
Word.Range

Une autre gamme.

Retours

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml

// Expands to the selection when both ranges belong to the same story.
await Word.run(async (context) => {
    const firstRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const selection: Word.Range = context.document.getSelection();
    const expandedRange: Word.Range = firstRange.expandToOrNullObject(selection);
    expandedRange.load("text");
    await context.sync();
    if (expandedRange.isNullObject) {
        console.warn("The ranges cannot be combined. Select text in the main document body.");
        return;
    }
    console.log(`Expanded text: ${expandedRange.text}`);
});

getBookmarks(includeHidden, includeAdjacent)

Obtient les noms, tous les signets dans ou chevauchant la plage. Un signet est masqué si son nom commence par le caractère de soulignement.

getBookmarks(includeHidden?: boolean, includeAdjacent?: boolean): OfficeExtension.ClientResult<string[]>;

Paramètres

includeHidden

boolean

Facultatif. Indique s’il faut inclure les signets masqués. Par défaut false , les signets masqués sont exclus.

includeAdjacent

boolean

Facultatif. Indique s’il faut inclure les signets adjacents à la plage. Par défaut false , les signets adjacents sont exclus.

Retours

Remarques

Jeu d’API : WordApi 1.4

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/manage-range-bookmarks.yaml

// Gets the names of bookmarks within or overlapping the first paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const bookmarkNames: OfficeExtension.ClientResult<string[]> = paragraphRange.getBookmarks(false, true);
    await context.sync();
    console.log("Bookmark names:", bookmarkNames.value);
});

getComments()

Obtient les commentaires associés à la plage.

getComments(): Word.CommentCollection;

Retours

Objet CommentCollection qui contient tous les commentaires associés à la plage.

Remarques

Jeu 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 selected content.
await Word.run(async (context) => {
  const comments: Word.CommentCollection = context.document.getSelection().getComments();

  // Load objects to log in the console.
  comments.load();
  await context.sync();

  console.log("Comments:", comments);
});

getContentControls(options)

Obtient les contrôles de contenu actuellement pris en charge dans la plage.

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

Paramètres

options
Word.ContentControlOptions

Facultatif. Les options qui définissent les contrôles de contenu qui sont renvoyés.

Retours

Remarques

Jeu 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 renvoyés. Notez qu’une exception sera levée lors de l’utilisation des 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.

Exemples

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

// Deletes the first checkbox content control found in the selection.
await Word.run(async (context) => {
  const selectedRange: Word.Range = context.document.getSelection();
  let selectedContentControl = selectedRange
    .getContentControls({
      types: [Word.ContentControlType.checkBox]
    })
    .getFirstOrNullObject();
  selectedContentControl.load("id");

  await context.sync();

  if (selectedContentControl.isNullObject) {
    const parentContentControl: Word.ContentControl = selectedRange.parentContentControl;
    parentContentControl.load("id,type");
    await context.sync();

    if (parentContentControl.isNullObject || parentContentControl.type !== Word.ContentControlType.checkBox) {
      console.warn("No checkbox content control is currently selected.");
      return;
    } else {
      selectedContentControl = parentContentControl;
    }
  }

  console.log(`About to delete checkbox content control with id: ${selectedContentControl.id}`);
  selectedContentControl.delete(false);
  await context.sync();

  console.log("Deleted checkbox content control.");
});

getHtml()

Obtient une représentation HTML de l’objet Range . Dans une page web ou une visionneuse HTML, la mise en forme correspond étroitement, mais pas exactement, à la mise en forme du document. Cette méthode ne renvoie 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 Range.getOoxml() et convertissez le XML renvoyé en HTML.

getHtml(): OfficeExtension.ClientResult<string>;

Retours

Remarques

Jeu d’API : WordApi 1.1

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml

// Reads an HTML representation of the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const html: OfficeExtension.ClientResult<string> = paragraphRange.getHtml();
    await context.sync();
    console.log(`Range HTML: ${html.value}`);
});

getHyperlinkRanges()

Obtient les plages enfants d’un lien hypertexte au sein de la plage.

getHyperlinkRanges(): Word.RangeCollection;

Retours

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Reads the text and destinations of hyperlinks in the document body range.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const hyperlinkRanges: Word.RangeCollection = bodyRange.getHyperlinkRanges();
    hyperlinkRanges.load("items/text,items/hyperlink");
    await context.sync();
    console.log(`Hyperlinks found: ${hyperlinkRanges.items.length}`);
    hyperlinkRanges.items.forEach((hyperlinkRange: Word.Range) => {
        console.log({ text: hyperlinkRange.text, hyperlink: hyperlinkRange.hyperlink });
    });
});

getNextTextRange(endingMarks, trimSpacing)

Obtient la plage de texte suivante à l’aide de signes de ponctuation et d’autres signes de fin. Génère une ItemNotFound erreur si cette plage de texte est la dernière.

getNextTextRange(endingMarks: string[], trimSpacing?: boolean): Word.Range;

Paramètres

endingMarks

string[]

Les signes de ponctuation et les autres signes de fin sous la forme d’un tableau de chaînes.

trimSpacing

boolean

Facultatif. Indique s’il faut supprimer les caractères d’espacement (espaces, tabulations, sauts de colonne et marques de fin de paragraphe) du début et de la fin de la plage renvoyée. Par défaut false , les caractères d’espacement au début et à la fin de la plage sont inclus.

Retours

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/split-words-of-first-paragraph.yaml

// Gets the sentence following the first sentence in the document.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const firstSentence: Word.Range = paragraphRange.getTextRanges(["?", "."], true).getFirst();
    const nextSentence: Word.Range = firstSentence.getNextTextRange(["?", "."], true);
    nextSentence.load("text");
    await context.sync();
    console.log(`Next sentence: ${nextSentence.text}`);
});

getNextTextRangeOrNullObject(endingMarks, trimSpacing)

Obtient la plage de texte suivante à l’aide de signes de ponctuation et d’autres signes de fin. Si cette plage de texte est la dernière, cette méthode renvoie un objet dont la isNullObject propriété est définie sur true. Pour plus d’informations, consultez * Méthodes et propriétés d’OrNullObject.

getNextTextRangeOrNullObject(endingMarks: string[], trimSpacing?: boolean): Word.Range;

Paramètres

endingMarks

string[]

Les signes de ponctuation et les autres signes de fin sous la forme d’un tableau de chaînes.

trimSpacing

boolean

Facultatif. Indique s’il faut supprimer les caractères d’espacement (espaces, tabulations, sauts de colonne et marques de fin de paragraphe) du début et de la fin de la plage renvoyée. Par défaut false , les caractères d’espacement au début et à la fin de la plage sont inclus.

Retours

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/split-words-of-first-paragraph.yaml

// Checks for a sentence after the end of the document without throwing.
await Word.run(async (context) => {
    const endRange: Word.Range = context.document.body.getRange(Word.RangeLocation.end);
    const nextSentence: Word.Range = endRange.getNextTextRangeOrNullObject([".", "?"], true);
    nextSentence.load("text");
    await context.sync();
    if (nextSentence.isNullObject) {
        console.warn("There is no sentence after the end of the document.");
        return;
    }
    console.log(`Next sentence: ${nextSentence.text}`);
});

getOoxml()

Obtient la représentation OOXML de l’objet Range .

getOoxml(): OfficeExtension.ClientResult<string>;

Retours

Remarques

Jeu d’API : WordApi 1.1

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml

// Reads the OOXML representation of the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const ooxml: OfficeExtension.ClientResult<string> = paragraphRange.getOoxml();
    await context.sync();
    console.log(`Range OOXML: ${ooxml.value}`);
});

getRange(rangeLocation)

Clone l’objet Range ou obtient le point de début ou de fin de la plage en tant que nouvelle 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 whole,start , end, afterou .content

Retours

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-dropdown-list-content-control.yaml

// Places a dropdown list content control at the end of the selection.
await Word.run(async (context) => {
  let selection = context.document.getSelection();
  selection.getRange(Word.RangeLocation.end).insertContentControl(Word.ContentControlType.dropDownList);
  await context.sync();

  console.log("Dropdown list content control inserted at the end of the selection.");
});

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

Jeu d’API : WordApi 1.4

Exemples

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

// Gets the reviewed text.
await Word.run(async (context) => {
  const range: Word.Range = context.document.getSelection();
  const before = range.getReviewedText(Word.ChangeTrackingVersion.original);
  const after = range.getReviewedText(Word.ChangeTrackingVersion.current);

  await context.sync();

  console.log("Reviewed text (before):", before.value, "Reviewed text (after):", after.value);
});

getReviewedText(changeTrackingVersion)

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

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

Paramètres

changeTrackingVersion

"Original" | "Current"

Facultatif. La valeur doit être original ou current. La valeur par défaut est current.

Retours

Remarques

Jeu d’API : WordApi 1.4

getTextRanges(endingMarks, trimSpacing)

Obtient les plages enfants de texte dans la plage à l’aide de signes de ponctuation et d’autres signes de fin.

getTextRanges(endingMarks: string[], trimSpacing?: boolean): Word.RangeCollection;

Paramètres

endingMarks

string[]

Les signes de ponctuation et les autres signes de fin sous la forme d’un tableau de chaînes.

trimSpacing

boolean

Facultatif. Indique s’il faut supprimer les caractères d’espacement (espaces, tabulations, sauts de colonne et marques de fin de paragraphe) du début et de la fin des plages renvoyées dans la collection de plages. Par défaut false , les caractères d’espacement au début et à la fin des plages sont inclus dans la collection de plages.

Retours

Remarques

Jeu d’API : WordApi 1.3

Exemples

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

// Gets complete sentences from the insertion point to the end of its paragraph.
await Word.run(async (context) => {
  const selection: Word.Range = context.document.getSelection();
  const sentences: Word.RangeCollection = selection.getTextRanges(["."], false);
  sentences.load("$none");
  await context.sync();

  const firstSentence: Word.Range = sentences.items[0];
  const paragraphEnd: Word.Range = selection.paragraphs.getFirst().getRange(Word.RangeLocation.end);
  const remainingRange: Word.Range = firstSentence.expandTo(paragraphEnd);
  const sentencesToTheEndOfParagraph: Word.RangeCollection = remainingRange.getTextRanges(["."], false);
  sentencesToTheEndOfParagraph.load("text");
  await context.sync();

  console.log("Sentences from the current sentence to the paragraph end:");
  for (let i = 0; i < sentencesToTheEndOfParagraph.items.length; i++) {
    console.log(sentencesToTheEndOfParagraph.items[i].text);
  }
});

getTrackedChanges()

Obtient la collection des TrackedChange objets de la plage.

getTrackedChanges(): Word.TrackedChangeCollection;

Retours

Remarques

Jeu 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 the tracked changes inside the first paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const trackedChanges: Word.TrackedChangeCollection = paragraphRange.getTrackedChanges();
    trackedChanges.load("items/author,items/text,items/type");
    await context.sync();
    console.log(`Tracked changes in the first paragraph: ${trackedChanges.items.length}`);
    trackedChanges.items.forEach((change: Word.TrackedChange) => {
        console.log({ author: change.author, text: change.text, type: change.type });
    });
});

highlight()

Met en surbrillance la plage temporairement sans modifier le contenu du document. Pour mettre en surbrillance le texte de façon permanente, définissez la valeur de font.highlightColorla plage.

highlight(): void;

Retours

void

Remarques

Jeu d’API : WordApi 1.8

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/scroll-to-range.yaml

// Temporarily highlights the final paragraph without changing its formatting.
await Word.run(async (context) => {
    const lastRange: Word.Range = context.document.body.paragraphs.getLast().getRange();
    lastRange.highlight();
    await context.sync();
    console.log("Temporarily highlighted the final paragraph.");
});

insertBookmark(name)

Insère un signet sur la plage. Si un signet du même nom existe quelque part, il est supprimé en premier.

insertBookmark(name: string): void;

Paramètres

name

string

Nom de signet qui ne respecte pas la casse. Seuls les caractères alphanumériques et les traits de soulignement sont pris en charge. Il doit commencer par une lettre, mais si vous souhaitez marquer le signet comme masqué, commencez le nom par un trait de soulignement. Les noms ne doivent pas comporter plus de 40 caractères.

Retours

void

Remarques

Jeu d’API : WordApi 1.4

Remarque : les conditions d’insertion d’un signet sont similaires à celles de l’interface utilisateur de Word. Pour en savoir plus sur la gestion des signets dans l’interface utilisateur de Word, voir Ajouter ou supprimer des signets dans un document Word ou un message Outlook.

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/manage-range-bookmarks.yaml

// Names the first paragraph range, replacing any existing bookmark with this name.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    paragraphRange.insertBookmark("RangeSampleSummary");
    await context.sync();
    console.log("Inserted the RangeSampleSummary bookmark. Get bookmark names to verify it.");
});

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.before | Word.InsertLocation.after | "Before" | "After"): void;

Paramètres

breakType

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

Type de pause à ajouter.

insertLocation

before | after | "Before" | "After"

La valeur doit être before ou after.

Retours

void

Remarques

Jeu d’API : WordApi 1.1

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Inserts a page break after the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    paragraphRange.insertBreak(Word.BreakType.page, Word.InsertLocation.after);
    await context.sync();
    console.log("Inserted a page break after the summary.");
});

insertCanvas(insertShapeOptions)

Insère une zone de dessin flottante devant le texte avec son ancrage au début de la plage.

insertCanvas(insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;

Paramètres

insertShapeOptions
Word.InsertShapeOptions

Facultatif. Emplacement et taille de la zone de dessin. L’emplacement et la taille par défaut sont (0, 0, 300, 200).

Retours

Remarques

Jeu d’API : WordApiDesktop 1.2

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/45-shapes/manage-canvases.yaml

await Word.run(async (context) => {
  // Inserts a canvas in the document.
  const canvasShape: Word.Shape = context.document.getSelection().insertCanvas();
  canvasShape.load();
  await context.sync();

  canvasShape.select();
  console.log("Inserted canvas:", canvasShape);

  const canvas: Word.Canvas = canvasShape.canvas;
  canvas.load("shape,shapes");
  await context.sync();

  console.log("Canvas object:", canvas);
});

insertComment(commentText)

Insérez un commentaire sur la plage.

insertComment(commentText: string): Word.Comment;

Paramètres

commentText

string

Texte du commentaire à insérer.

Retours

L’objet Comment qui a été inséré.

Remarques

Jeu 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

// Sets a comment on the selected content.
await Word.run(async (context) => {
  const text = (document.getElementById("comment-text") as HTMLInputElement).value;
  const comment: Word.Comment = context.document.getSelection().insertComment(text);

  // Load object to log in the console.
  comment.load();
  await context.sync();

  console.log("Comment inserted:", comment);
});

insertContentControl(contentControlType)

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

insertContentControl(contentControlType?: Word.ContentControlType.richText | Word.ContentControlType.plainText | Word.ContentControlType.checkBox | Word.ContentControlType.dropDownList | Word.ContentControlType.comboBox | Word.ContentControlType.buildingBlockGallery | Word.ContentControlType.datePicker | Word.ContentControlType.repeatingSection | Word.ContentControlType.picture | Word.ContentControlType.group | "RichText" | "PlainText" | "CheckBox" | "DropDownList" | "ComboBox" | "BuildingBlockGallery" | "DatePicker" | "RepeatingSection" | "Picture" | "Group"): Word.ContentControl;

Paramètres

contentControlType

richText | plainText | checkBox | dropDownList | comboBox | buildingBlockGallery | datePicker | repeatingSection | picture | group | "RichText" | "PlainText" | "CheckBox" | "DropDownList" | "ComboBox" | "BuildingBlockGallery" | "DatePicker" | "RepeatingSection" | "Picture" | "Group"

Facultatif. Type de contrôle de contenu à insérer. Doit être richText, , plainTextcheckBox,dropDownList , comboBox, buildingBlockGallerydatePickerrepeatingSectionpicture, ou .group La valeur par défaut est richText.

Retours

Remarques

Jeu 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. dropDownList et comboBox la prise en charge a été ajoutée dans WordAPI 1.9. Prise en charge de buildingBlockGallery,datePicker , picturegroup, et repeatingSection a été ajouté dans WordApiDesktop 1.3.

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/90-scenarios/doc-assembly.yaml

// Simulates creation of a template. First searches the document for instances of the string "Contractor",
// then changes the format  of each search result,
// then wraps each search result within a content control,
// finally sets a tag and title property on each content control.
await Word.run(async (context) => {
    const results: Word.RangeCollection = context.document.body.search("Contractor");
    results.load("font/bold");

    // Check to make sure these content controls haven't been added yet.
    const customerContentControls: Word.ContentControlCollection = context.document.contentControls.getByTag("customer");
    customerContentControls.load("text");
    await context.sync();

  if (customerContentControls.items.length === 0) {
    for (let i = 0; i < results.items.length; i++) {
        results.items[i].font.bold = true;
        let cc: Word.ContentControl = results.items[i].insertContentControl();
        cc.tag = "customer";  // This value is used in the next step of this sample.
        cc.title = "Customer Name " + i;
    }
  }
    await context.sync();
});

insertEndnote(insertText)

Insère une note de fin. La référence de note de fin est placée après la plage.

insertEndnote(insertText?: string): Word.NoteItem;

Paramètres

insertText

string

Facultatif. Texte à insérer dans le corps de la note de fin. La valeur par défaut est « ».

Retours

Remarques

Jeu 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

// Adds an endnote to the first paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const endnote: Word.NoteItem = paragraphRange.insertEndnote("Source: the sample document.");
    await context.sync();
    console.log("Inserted an endnote. Its text appears at the end of the document.");
});

insertField(insertLocation, fieldType, text, removeFormatting)

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

insertField(insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After", fieldType?: Word.FieldType, text?: string, removeFormatting?: boolean): Word.Field;

Paramètres

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

Emplacement relatif à la plage dans laquelle le champ sera inséré. La valeur doit être replace, , endstart, beforeou after.

fieldType
Word.FieldType

Facultatif. Peut être n’importe quelle FieldType valeur. La valeur par défaut est empty.

text

string

Facultatif. Propriétés ou options supplémentaires si nécessaire pour le type de champ spécifié.

removeFormatting

boolean

Facultatif. true Pour supprimer la mise en forme appliquée au champ lors des mises à jour, false dans le cas contraire. La valeur par défaut est false.

Retours

Remarques

Jeu d’API : WordApi 1.5

Important : Dans Word sur Windows et sur Mac, l’API prend en charge l’insertion et la gestion de tous les types répertoriés dans Word. FieldType except Word.FieldType.others. Dans Word sur le web, les champs sont principalement en lecture seule. Pour plus d’informations, voir Utiliser des champs dans votre complément Word.

Exemples

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

// Inserts a Date field before selection.
await Word.run(async (context) => {
  const range: Word.Range = context.document.getSelection().getRange();

  const field: Word.Field = range.insertField(Word.InsertLocation.before, Word.FieldType.date, '\\@ "M/d/yyyy h:mm am/pm"', true);

  field.load("result,code");
  await context.sync();

  if (field.isNullObject) {
    console.log("There are no fields in this document.");
  } else {
    console.log("Code of the field: " + field.code, "Result of the field: " + JSON.stringify(field.result));
  }
});

insertField(insertLocation, fieldType, text, removeFormatting)

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

insertField(insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After", fieldType?: "Addin" | "AddressBlock" | "Advance" | "Ask" | "Author" | "AutoText" | "AutoTextList" | "BarCode" | "Bibliography" | "BidiOutline" | "Citation" | "Comments" | "Compare" | "CreateDate" | "Data" | "Database" | "Date" | "DisplayBarcode" | "DocProperty" | "DocVariable" | "EditTime" | "Embedded" | "EQ" | "Expression" | "FileName" | "FileSize" | "FillIn" | "FormCheckbox" | "FormDropdown" | "FormText" | "GotoButton" | "GreetingLine" | "Hyperlink" | "If" | "Import" | "Include" | "IncludePicture" | "IncludeText" | "Index" | "Info" | "Keywords" | "LastSavedBy" | "Link" | "ListNum" | "MacroButton" | "MergeBarcode" | "MergeField" | "MergeRec" | "MergeSeq" | "Next" | "NextIf" | "NoteRef" | "NumChars" | "NumPages" | "NumWords" | "OCX" | "Page" | "PageRef" | "Print" | "PrintDate" | "Private" | "Quote" | "RD" | "Ref" | "RevNum" | "SaveDate" | "Section" | "SectionPages" | "Seq" | "Set" | "Shape" | "SkipIf" | "StyleRef" | "Subject" | "Subscriber" | "Symbol" | "TA" | "TC" | "Template" | "Time" | "Title" | "TOA" | "TOC" | "UserAddress" | "UserInitials" | "UserName" | "XE" | "Empty" | "Others" | "Undefined", text?: string, removeFormatting?: boolean): Word.Field;

Paramètres

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

Emplacement relatif à la plage dans laquelle le champ sera inséré. La valeur doit être replace, , endstart, beforeou after.

fieldType

"Addin" | "AddressBlock" | "Advance" | "Ask" | "Author" | "AutoText" | "AutoTextList" | "BarCode" | "Bibliography" | "BidiOutline" | "Citation" | "Comments" | "Compare" | "CreateDate" | "Data" | "Database" | "Date" | "DisplayBarcode" | "DocProperty" | "DocVariable" | "EditTime" | "Embedded" | "EQ" | "Expression" | "FileName" | "FileSize" | "FillIn" | "FormCheckbox" | "FormDropdown" | "FormText" | "GotoButton" | "GreetingLine" | "Hyperlink" | "If" | "Import" | "Include" | "IncludePicture" | "IncludeText" | "Index" | "Info" | "Keywords" | "LastSavedBy" | "Link" | "ListNum" | "MacroButton" | "MergeBarcode" | "MergeField" | "MergeRec" | "MergeSeq" | "Next" | "NextIf" | "NoteRef" | "NumChars" | "NumPages" | "NumWords" | "OCX" | "Page" | "PageRef" | "Print" | "PrintDate" | "Private" | "Quote" | "RD" | "Ref" | "RevNum" | "SaveDate" | "Section" | "SectionPages" | "Seq" | "Set" | "Shape" | "SkipIf" | "StyleRef" | "Subject" | "Subscriber" | "Symbol" | "TA" | "TC" | "Template" | "Time" | "Title" | "TOA" | "TOC" | "UserAddress" | "UserInitials" | "UserName" | "XE" | "Empty" | "Others" | "Undefined"

Facultatif. Peut être n’importe quelle FieldType valeur. La valeur par défaut est empty.

text

string

Facultatif. Propriétés ou options supplémentaires si nécessaire pour le type de champ spécifié.

removeFormatting

boolean

Facultatif. true Pour supprimer la mise en forme appliquée au champ lors des mises à jour, false dans le cas contraire. La valeur par défaut est false.

Retours

Remarques

Jeu d’API : WordApi 1.5

Important : Dans Word sur Windows et sur Mac, l’API prend en charge l’insertion et la gestion de tous les types répertoriés dans Word. FieldType except Word.FieldType.others. Dans Word sur le web, les champs sont principalement en lecture seule. Pour plus d’informations, voir Utiliser des champs dans votre complément Word.

insertFileFromBase64(base64File, insertLocation)

Insère un document à l’emplacement spécifié. La taille maximale du document inséré est de 4 Mo.

insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.Range;

Paramètres

base64File

string

Le contenu codé en Base64 d’un fichier .docx.

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

La valeur doit être replace, , endstart, beforeou after.

Retours

Remarques

Jeu d’API : WordApi 1.1

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 adaptée à votre scénario.

L’insertion n’est pas prise en charge si le document inséré contient du contenu lié ou externe. Si c’est le cas, cette méthode renvoie une InvalidArgument erreur.

Lors de l’insertion d’un document, les paramètres du document ne sont pas conservés.

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml

// Replaces the first paragraph with the contents of a small embedded DOCX file.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    // The DOCX contains one paragraph: "Imported project update."
    const base64File: string = "UEsDBBQAAAAIAAAAIVD3S4B1wgAAAHYBAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbH2QuQ7CMAyGX6XKiqgRAwOiLMAKDLyAlbptRC7FLsfbk3INCBjt//gsLw7XSFxcnPVcqU4kzgFYd+SQyxDJZ6UJyaHkMbUQUR+xJZhOJjPQwQt5GcvQoZaLNTXYWyk2l7xmE3ylEllWxephHFiVwhit0ShZh5OvPyjjJ6HMybuHOxN5lA0KvhIG5TfgmdudKCVTU7HHJFt02QXnkGqog+5dTpb/a77cGZrGaHrnh7aYgiZm41tny7fi0PjX/XB/9/IGUEsDBBQAAAAIAAAAIVBhey9DiQAAAPIAAAALAAAAX3JlbHMvLnJlbHONzzsOAiEQBuCrEA6ws1pYGKCy2dZ4AQLDIy6PDBj19lJYrMbCcuaffH9GnHHVPZbcQqyNPdKam+Sh93oEaCZg0m0qFfNIXKGk+xjJQ9Xmqj3Cfp4PQFuDK7E12WIlp8XuOLs8K/5jF+eiwVMxt4S5/6j4uhiyJo9d8nshC/a9ngbLQQn4eFG9AFBLAwQUAAAACAAAACFQZhg8uIUAAAC1AAAAEQAAAHdvcmQvZG9jdW1lbnQueG1sRY47DsIwDIavUvUAdcXAEIXubFwhJKYtquPIcZVye5IysHyW/T9kW0xgvxNG7Q7aYjbl1i+qyQBkvyC5PHDCWLUXCzmtq8xQWEIS9pjzGmfa4DKOVyC3xn6yxTw5fNpMDdKg050Si2Loau6NXrs9Bac4WGhqo5w8M7kaHgLn4VcG/0enL1BLAQIUABQAAAAIAAAAIVD3S4B1wgAAAHYBAAATAAAAAAAAAAAAAACAAQAAAABbQ29udGVudF9UeXBlc10ueG1sUEsBAhQAFAAAAAgAAAAhUGF7L0OJAAAA8gAAAAsAAAAAAAAAAAAAAIAB8wAAAF9yZWxzLy5yZWxzUEsBAhQAFAAAAAgAAAAhUGYYPLiFAAAAtQAAABEAAAAAAAAAAAAAAIABpQEAAHdvcmQvZG9jdW1lbnQueG1sUEsFBgAAAAADAAMAuQAAAFkCAAAAAA==";
    const insertedRange: Word.Range = paragraphRange.insertFileFromBase64(base64File, Word.InsertLocation.replace);
    await context.sync();
    console.log("Inserted the embedded document's project update.");
});

insertFootnote(insertText)

insère une note de bas de page. La référence de note de bas de page est placée après la plage.

insertFootnote(insertText?: string): Word.NoteItem;

Paramètres

insertText

string

Facultatif. Texte à insérer dans le corps de la note de bas de page. La valeur par défaut est « ».

Retours

Remarques

Jeu 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

// Sets a footnote on the selected content.
await Word.run(async (context) => {
  const text = (document.getElementById("input-footnote") as HTMLInputElement).value;
  const footnote: Word.NoteItem = context.document.getSelection().insertFootnote(text);
  await context.sync();

  console.log("Inserted footnote.");
});

insertGeometricShape(geometricShapeType, insertShapeOptions)

Insère une forme géométrique devant le texte avec son ancrage au début de la plage.

insertGeometricShape(geometricShapeType: Word.GeometricShapeType, insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;

Paramètres

geometricShapeType
Word.GeometricShapeType

Type géométrique de la forme à insérer.

insertShapeOptions
Word.InsertShapeOptions

Facultatif. Emplacement et taille de la forme géométrique. L’emplacement et la taille par défaut sont (0, 0, 100, 100).

Retours

Remarques

Jeu d’API : WordApiDesktop 1.2

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/45-shapes/manage-geometric-shapes.yaml

await Word.run(async (context) => {
  // Inserts a moon geometric shape at the beginning of the selection.
  const selection: Word.Range = context.document.getSelection();
  const shapeOptions: Word.InsertShapeOptions = {
    height: 120,
    width: 120,
    left: 120,
  };
  selection.insertGeometricShape(Word.GeometricShapeType.moon, shapeOptions);
  await context.sync();

  console.log("Inserted a moon.");
});

insertGeometricShape(geometricShapeType, insertShapeOptions)

Insère une forme géométrique devant le texte avec son ancrage au début de la plage.

insertGeometricShape(geometricShapeType: "LineInverse" | "Triangle" | "RightTriangle" | "Rectangle" | "Diamond" | "Parallelogram" | "Trapezoid" | "NonIsoscelesTrapezoid" | "Pentagon" | "Hexagon" | "Heptagon" | "Octagon" | "Decagon" | "Dodecagon" | "Star4" | "Star5" | "Star6" | "Star7" | "Star8" | "Star10" | "Star12" | "Star16" | "Star24" | "Star32" | "RoundRectangle" | "Round1Rectangle" | "Round2SameRectangle" | "Round2DiagonalRectangle" | "SnipRoundRectangle" | "Snip1Rectangle" | "Snip2SameRectangle" | "Snip2DiagonalRectangle" | "Plaque" | "Ellipse" | "Teardrop" | "HomePlate" | "Chevron" | "PieWedge" | "Pie" | "BlockArc" | "Donut" | "NoSmoking" | "RightArrow" | "LeftArrow" | "UpArrow" | "DownArrow" | "StripedRightArrow" | "NotchedRightArrow" | "BentUpArrow" | "LeftRightArrow" | "UpDownArrow" | "LeftUpArrow" | "LeftRightUpArrow" | "QuadArrow" | "LeftArrowCallout" | "RightArrowCallout" | "UpArrowCallout" | "DownArrowCallout" | "LeftRightArrowCallout" | "UpDownArrowCallout" | "QuadArrowCallout" | "BentArrow" | "UturnArrow" | "CircularArrow" | "LeftCircularArrow" | "LeftRightCircularArrow" | "CurvedRightArrow" | "CurvedLeftArrow" | "CurvedUpArrow" | "CurvedDownArrow" | "SwooshArrow" | "Cube" | "Can" | "LightningBolt" | "Heart" | "Sun" | "Moon" | "SmileyFace" | "IrregularSeal1" | "IrregularSeal2" | "FoldedCorner" | "Bevel" | "Frame" | "HalfFrame" | "Corner" | "DiagonalStripe" | "Chord" | "Arc" | "LeftBracket" | "RightBracket" | "LeftBrace" | "RightBrace" | "BracketPair" | "BracePair" | "Callout1" | "Callout2" | "Callout3" | "AccentCallout1" | "AccentCallout2" | "AccentCallout3" | "BorderCallout1" | "BorderCallout2" | "BorderCallout3" | "AccentBorderCallout1" | "AccentBorderCallout2" | "AccentBorderCallout3" | "WedgeRectCallout" | "WedgeRRectCallout" | "WedgeEllipseCallout" | "CloudCallout" | "Cloud" | "Ribbon" | "Ribbon2" | "EllipseRibbon" | "EllipseRibbon2" | "LeftRightRibbon" | "VerticalScroll" | "HorizontalScroll" | "Wave" | "DoubleWave" | "Plus" | "FlowChartProcess" | "FlowChartDecision" | "FlowChartInputOutput" | "FlowChartPredefinedProcess" | "FlowChartInternalStorage" | "FlowChartDocument" | "FlowChartMultidocument" | "FlowChartTerminator" | "FlowChartPreparation" | "FlowChartManualInput" | "FlowChartManualOperation" | "FlowChartConnector" | "FlowChartPunchedCard" | "FlowChartPunchedTape" | "FlowChartSummingJunction" | "FlowChartOr" | "FlowChartCollate" | "FlowChartSort" | "FlowChartExtract" | "FlowChartMerge" | "FlowChartOfflineStorage" | "FlowChartOnlineStorage" | "FlowChartMagneticTape" | "FlowChartMagneticDisk" | "FlowChartMagneticDrum" | "FlowChartDisplay" | "FlowChartDelay" | "FlowChartAlternateProcess" | "FlowChartOffpageConnector" | "ActionButtonBlank" | "ActionButtonHome" | "ActionButtonHelp" | "ActionButtonInformation" | "ActionButtonForwardNext" | "ActionButtonBackPrevious" | "ActionButtonEnd" | "ActionButtonBeginning" | "ActionButtonReturn" | "ActionButtonDocument" | "ActionButtonSound" | "ActionButtonMovie" | "Gear6" | "Gear9" | "Funnel" | "MathPlus" | "MathMinus" | "MathMultiply" | "MathDivide" | "MathEqual" | "MathNotEqual" | "CornerTabs" | "SquareTabs" | "PlaqueTabs" | "ChartX" | "ChartStar" | "ChartPlus", insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;

Paramètres

geometricShapeType

"LineInverse" | "Triangle" | "RightTriangle" | "Rectangle" | "Diamond" | "Parallelogram" | "Trapezoid" | "NonIsoscelesTrapezoid" | "Pentagon" | "Hexagon" | "Heptagon" | "Octagon" | "Decagon" | "Dodecagon" | "Star4" | "Star5" | "Star6" | "Star7" | "Star8" | "Star10" | "Star12" | "Star16" | "Star24" | "Star32" | "RoundRectangle" | "Round1Rectangle" | "Round2SameRectangle" | "Round2DiagonalRectangle" | "SnipRoundRectangle" | "Snip1Rectangle" | "Snip2SameRectangle" | "Snip2DiagonalRectangle" | "Plaque" | "Ellipse" | "Teardrop" | "HomePlate" | "Chevron" | "PieWedge" | "Pie" | "BlockArc" | "Donut" | "NoSmoking" | "RightArrow" | "LeftArrow" | "UpArrow" | "DownArrow" | "StripedRightArrow" | "NotchedRightArrow" | "BentUpArrow" | "LeftRightArrow" | "UpDownArrow" | "LeftUpArrow" | "LeftRightUpArrow" | "QuadArrow" | "LeftArrowCallout" | "RightArrowCallout" | "UpArrowCallout" | "DownArrowCallout" | "LeftRightArrowCallout" | "UpDownArrowCallout" | "QuadArrowCallout" | "BentArrow" | "UturnArrow" | "CircularArrow" | "LeftCircularArrow" | "LeftRightCircularArrow" | "CurvedRightArrow" | "CurvedLeftArrow" | "CurvedUpArrow" | "CurvedDownArrow" | "SwooshArrow" | "Cube" | "Can" | "LightningBolt" | "Heart" | "Sun" | "Moon" | "SmileyFace" | "IrregularSeal1" | "IrregularSeal2" | "FoldedCorner" | "Bevel" | "Frame" | "HalfFrame" | "Corner" | "DiagonalStripe" | "Chord" | "Arc" | "LeftBracket" | "RightBracket" | "LeftBrace" | "RightBrace" | "BracketPair" | "BracePair" | "Callout1" | "Callout2" | "Callout3" | "AccentCallout1" | "AccentCallout2" | "AccentCallout3" | "BorderCallout1" | "BorderCallout2" | "BorderCallout3" | "AccentBorderCallout1" | "AccentBorderCallout2" | "AccentBorderCallout3" | "WedgeRectCallout" | "WedgeRRectCallout" | "WedgeEllipseCallout" | "CloudCallout" | "Cloud" | "Ribbon" | "Ribbon2" | "EllipseRibbon" | "EllipseRibbon2" | "LeftRightRibbon" | "VerticalScroll" | "HorizontalScroll" | "Wave" | "DoubleWave" | "Plus" | "FlowChartProcess" | "FlowChartDecision" | "FlowChartInputOutput" | "FlowChartPredefinedProcess" | "FlowChartInternalStorage" | "FlowChartDocument" | "FlowChartMultidocument" | "FlowChartTerminator" | "FlowChartPreparation" | "FlowChartManualInput" | "FlowChartManualOperation" | "FlowChartConnector" | "FlowChartPunchedCard" | "FlowChartPunchedTape" | "FlowChartSummingJunction" | "FlowChartOr" | "FlowChartCollate" | "FlowChartSort" | "FlowChartExtract" | "FlowChartMerge" | "FlowChartOfflineStorage" | "FlowChartOnlineStorage" | "FlowChartMagneticTape" | "FlowChartMagneticDisk" | "FlowChartMagneticDrum" | "FlowChartDisplay" | "FlowChartDelay" | "FlowChartAlternateProcess" | "FlowChartOffpageConnector" | "ActionButtonBlank" | "ActionButtonHome" | "ActionButtonHelp" | "ActionButtonInformation" | "ActionButtonForwardNext" | "ActionButtonBackPrevious" | "ActionButtonEnd" | "ActionButtonBeginning" | "ActionButtonReturn" | "ActionButtonDocument" | "ActionButtonSound" | "ActionButtonMovie" | "Gear6" | "Gear9" | "Funnel" | "MathPlus" | "MathMinus" | "MathMultiply" | "MathDivide" | "MathEqual" | "MathNotEqual" | "CornerTabs" | "SquareTabs" | "PlaqueTabs" | "ChartX" | "ChartStar" | "ChartPlus"

Type géométrique de la forme à insérer.

insertShapeOptions
Word.InsertShapeOptions

Facultatif. Emplacement et taille de la forme géométrique. L’emplacement et la taille par défaut sont (0, 0, 100, 100).

Retours

Remarques

Jeu d’API : WordApiDesktop 1.2

insertHtml(html, insertLocation)

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

insertHtml(html: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.Range;

Paramètres

html

string

Code HTML à insérer.

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

La valeur doit être replace, , endstart, beforeou after.

Retours

Remarques

Jeu d’API : WordApi 1.1

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml

// Replaces the first paragraph's content with formatted HTML.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const insertedRange: Word.Range = paragraphRange.insertHtml("<b>Project update:</b> <i>ready for review.</i>", Word.InsertLocation.replace);
    await context.sync();
    console.log("Inserted bold and italic text from HTML.");
});

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

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

insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.InlinePicture;

Paramètres

base64EncodedImage

string

Image codée en Base64 à insérer.

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

La valeur doit être replace, , endstart, beforeou after.

Retours

Remarques

Jeu d’API : WordApi 1.2

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/45-shapes/manage-shapes-text-boxes.yaml

await Word.run(async (context) => {
  // Inserts a picture at the start of the first text box.
  const firstShapeWithTextBox: Word.Shape = context.document.body.shapes
    .getByTypes([Word.ShapeType.textBox])
    .getFirst();
  firstShapeWithTextBox.load("type/body");
  await context.sync();

  const startRange: Word.Range = firstShapeWithTextBox.body.getRange(Word.RangeLocation.start);
  const newPic: Word.InlinePicture = startRange.insertInlinePictureFromBase64(
    getPictureBase64(),
    Word.InsertLocation.start
  );
  newPic.load();
  await context.sync();

  console.log("New inline picture properties:", newPic);
});

insertOoxml(ooxml, insertLocation)

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

insertOoxml(ooxml: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.Range;

Paramètres

ooxml

string

Code OOXML à insérer.

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

La valeur doit être replace, , endstart, beforeou after.

Retours

Remarques

Jeu d’API : WordApi 1.1

L’insertion n’est pas prise en charge si le contenu inséré contient du contenu lié ou externe. Si c’est le cas, cette méthode renvoie une InvalidArgument erreur.

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml

// Replaces the first paragraph with a bold paragraph from an OOXML package.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const ooxml: string =
        `<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: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:r><w:rPr><w:b/></w:rPr><w:t>Project update from OOXML.</w:t></w:r></w:p></w:body>
                </w:document></pkg:xmlData>
            </pkg:part>
        </pkg:package>`;
    const insertedRange: Word.Range = paragraphRange.insertOoxml(ooxml, Word.InsertLocation.replace);
    await context.sync();
    console.log("Inserted a bold paragraph from OOXML.");
});

insertParagraph(paragraphText, insertLocation)

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

insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation.before | Word.InsertLocation.after | "Before" | "After"): Word.Paragraph;

Paramètres

paragraphText

string

Texte de paragraphe à insérer.

insertLocation

before | after | "Before" | "After"

La valeur doit être before ou after.

Retours

Remarques

Jeu d’API : WordApi 1.1

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Adds a paragraph after the first paragraph range.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const newParagraph: Word.Paragraph = paragraphRange.insertParagraph("Additional project details.", Word.InsertLocation.after);
    await context.sync();
    console.log("Inserted a paragraph after the summary.");
});

insertPictureFromBase64(base64EncodedImage, insertShapeOptions)

Insère une image flottante devant le texte avec son ancrage au début de la plage.

insertPictureFromBase64(base64EncodedImage: string, insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;

Paramètres

base64EncodedImage

string

Image codée en Base64 à insérer.

insertShapeOptions
Word.InsertShapeOptions

Facultatif. Emplacement et taille de l’image. L’emplacement par défaut est (0, 0) et la taille par défaut est la taille d’origine de l’image.

Retours

Remarques

Jeu d’API : WordApiDesktop 1.2

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-layout-desktop.yaml

// Anchors a floating picture at the start of the first paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const pictureOptions: Word.InsertShapeOptions = { left: 20, top: 20, width: 90, height: 39 };
    const picture: Word.Shape = paragraphRange.insertPictureFromBase64(
        "iVBORw0KGgoAAAANSUhEUgAAAB4AAAANCAIAAAAxEEnAAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACFSURBVDhPtY1BEoQwDMP6/0+XgIMTBAeYoTqso9Rkx1zG+tNj1H94jgGzeNSjteO5vtQQuG2seO0av8LzGbe3anzRoJ4ybm/VeKEerAEbAUpW4aWQCmrGFWykRzGBCnYy2ha3oAIq2MloW9yCCqhgJ6NtcQsqoIKdjLbFLaiACnYyf2fODbrjZcXfr2F4AAAAAElFTkSuQmCC",
        pictureOptions
    );
    picture.name = "RangeSamplePicture";
    await context.sync();
    console.log("Inserted a floating picture. Get shapes to inspect it.");
});

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.before | Word.InsertLocation.after | "Before" | "After", values?: string[][]): Word.Table;

Paramètres

rowCount

number

Nombre de lignes du tableau.

columnCount

number

Nombre de colonnes du tableau.

insertLocation

before | after | "Before" | "After"

La valeur doit être before ou after.

values

string[][]

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

Retours

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml

// Adds a project status table after the last paragraph range.
await Word.run(async (context) => {
    const lastRange: Word.Range = context.document.body.paragraphs.getLast().getRange();
    const projectTable: Word.Table = lastRange.insertTable(2, 2, Word.InsertLocation.after, [
        ["Task", "Status"],
        ["Review", "Ready"]
    ]);
    await context.sync();
    console.log("Inserted a project status table.");
});

insertText(text, insertLocation)

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

insertText(text: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.Range;

Paramètres

text

string

Texte à insérer.

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

La valeur doit être replace, , endstart, beforeou after.

Retours

Remarques

Jeu d’API : WordApi 1.1

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Replaces the first paragraph's text without replacing its paragraph mark.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
    const insertedRange: Word.Range = paragraphRange.insertText("Updated project summary.", Word.InsertLocation.replace);
    await context.sync();
    console.log("Replaced the first paragraph's text.");
});

insertTextBox(text, insertShapeOptions)

Insère une zone de texte flottante devant le texte avec son ancrage au début de la plage.

insertTextBox(text?: string, insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;

Paramètres

text

string

Facultatif. Texte à insérer dans la zone de texte.

insertShapeOptions
Word.InsertShapeOptions

Facultatif. Emplacement et taille de la zone de texte. L’emplacement et la taille par défaut sont (0, 0, 100, 100).

Retours

Remarques

Jeu d’API : WordApiDesktop 1.2

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/45-shapes/manage-shapes-text-boxes.yaml

await Word.run(async (context) => {
  // Inserts a text box at the beginning of the selection.
  const range: Word.Range = context.document.getSelection();
  const insertShapeOptions: Word.InsertShapeOptions = {
    top: 0,
    left: 0,
    height: 100,
    width: 100
  };

  const newTextBox: Word.Shape = range.insertTextBox("placeholder text", insertShapeOptions);
  await context.sync();

  console.log("Inserted a text box at the beginning of the current selection.");
});

intersectWith(range)

Retourne une nouvelle plage en tant qu’intersection de cette plage avec une autre. Cette plage n’est pas modifiée. Génère une ItemNotFound erreur si les deux plages ne sont pas superposées ou adjacentes.

intersectWith(range: Word.Range): Word.Range;

Paramètres

range
Word.Range

Une autre gamme.

Retours

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml

// Gets the overlap between the document body and its first paragraph.
await Word.run(async (context) => {
    const bodyRange: Word.Range = context.document.body.getRange();
    const firstRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const overlap: Word.Range = bodyRange.intersectWith(firstRange);
    overlap.load("text");
    await context.sync();
    console.log(`Overlapping text: ${overlap.text}`);
});

intersectWithOrNullObject(range)

Retourne une nouvelle plage en tant qu’intersection de cette plage avec une autre. Cette plage n’est pas modifiée. Si les deux plages ne sont pas superposées ou adjacentes, cette méthode renvoie un objet dont la isNullObject propriété est définie sur true. Pour plus d’informations, consultez * Méthodes et propriétés d’OrNullObject.

intersectWithOrNullObject(range: Word.Range): Word.Range;

Paramètres

range
Word.Range

Une autre gamme.

Retours

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml

// Checks whether the selection overlaps the first paragraph.
await Word.run(async (context) => {
    const firstRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const selection: Word.Range = context.document.getSelection();
    const overlap: Word.Range = firstRange.intersectWithOrNullObject(selection);
    overlap.load("text");
    await context.sync();
    if (overlap.isNullObject) {
        console.warn("The selection does not overlap or adjoin the first paragraph.");
        return;
    }
    console.log(`Overlapping text: ${overlap.text}`);
});

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.RangeLoadOptions): Word.Range;

Paramètres

options
Word.Interfaces.RangeLoadOptions

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.Range;

Paramètres

propertyNames

string | string[]

Chaîne délimitée par des virgules ou tableau de chaînes spécifiant 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.Range;

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

removeHighlight()

Supprime la surbrillance ajoutée par la méthode, le highlight cas échéant.

removeHighlight(): void;

Retours

void

Remarques

Jeu d’API : WordApi 1.8

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/scroll-to-range.yaml

// Removes the temporary highlight from the final paragraph.
await Word.run(async (context) => {
    const lastRange: Word.Range = context.document.body.paragraphs.getLast().getRange();
    lastRange.removeHighlight();
    await context.sync();
    console.log("Removed the temporary highlight.");
});

search(searchText, searchOptions)

Effectue une recherche avec les options de recherche spécifiées sur l’étendue de l’objet Range . Les résultats de la recherche sont une collection d’objets Range .

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

Texte de recherche.

searchOptions

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

Facultatif. Options de la recherche.

Retours

Remarques

Jeu d’API : WordApi 1.1

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml

// Finds whole-word matches within the first paragraph.
await Word.run(async (context) => {
    const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
    const searchOptions: Word.SearchOptions = Word.SearchOptions.newObject(context);
    searchOptions.matchCase = false;
    searchOptions.matchWholeWord = true;
    const matches: Word.RangeCollection = paragraphRange.search("project", searchOptions);
    matches.load("items/text");
    await context.sync();
    console.log(`Matches found: ${matches.items.length}`);
    matches.items.forEach((match: Word.Range) => console.log(match.text));
});

select(selectionMode)

Sélectionne la plage 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 est la valeur par défaut.

Retours

void

Remarques

Jeu d’API : WordApi 1.1

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/scroll-to-range.yaml

// Selects the final paragraph and scrolls it into view.
await Word.run(async (context) => {
  const lastRange: Word.Range = context.document.body.paragraphs.getLast().getRange();
  lastRange.select();

  await context.sync();
});

select(selectionMode)

Sélectionne la plage et y accède via l’interface utilisateur de Word.

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

Paramètres

selectionMode

"Select" | "Start" | "End"

Facultatif. Le mode de sélection doit être select, start, ou end. select est la valeur par défaut.

Retours

void

Remarques

Jeu d’API : WordApi 1.1

set(properties, options)

Définit plusieurs propriétés d’un objet en même temps. Vous pouvez transmettre soit un objet ordinaire avec les propriétés appropriées, soit un autre objet API du même type.

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

Paramètres

properties
Word.Interfaces.RangeUpdateData

Objet JavaScript dont les propriétés sont structurées de façon isomorphe par rapport aux 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 de propriétés 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.Range): void;

Paramètres

properties
Word.Range

Retours

void

split(delimiters, multiParagraphs, trimDelimiters, trimSpacing)

Divise la plage en plages enfants à l’aide de délimiteurs.

split(delimiters: string[], multiParagraphs?: boolean, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection;

Paramètres

delimiters

string[]

Les délimiteurs sous la forme d’un tableau de chaînes.

multiParagraphs

boolean

Facultatif. Indique si une plage enfant renvoyée peut couvrir plusieurs paragraphes. Par défaut false , les limites de paragraphe sont également utilisées comme délimiteurs.

trimDelimiters

boolean

Facultatif. Indique s’il faut supprimer les délimiteurs des plages de la collection de plages. Par défaut false , les délimiteurs sont inclus dans les plages renvoyées dans la collection de plages.

trimSpacing

boolean

Facultatif. Indique s’il faut supprimer les caractères d’espacement (espaces, tabulations, sauts de colonne et marques de fin de paragraphe) du début et de la fin des plages renvoyées dans la collection de plages. Par défaut false , les caractères d’espacement au début et à la fin des plages sont inclus dans la collection de plages.

Retours

Remarques

Jeu d’API : WordApi 1.3

Exemples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/split-words-of-first-paragraph.yaml

// Splits the first paragraph into words and highlights them in sequence.
await Word.run(async (context) => {
  const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
  const words: Word.RangeCollection = paragraphRange.split([" "], false, true, true);
  words.load("text");

  await context.sync();

  for (let i = 0; i < words.items.length; i++) {
    if (i >= 1) {
      words.items[i - 1].font.highlightColor = "#FFFFFF";
    }
    words.items[i].font.highlightColor = "#FFFF00";

    await context.sync();
    await new Promise((resolve) => setTimeout(resolve, 200));
  }
});

toJSON()

Remplace la méthode JavaScript toJSON() afin de fournir une sortie plus utile lorsqu’un objet API est passé à JSON.stringify(). (JSON.stringify, à son tour, appelle la toJSON méthode de l’objet qui lui est passé.) Alors que l’objet d’origine Word.Range est un objet API, la toJSON méthode renvoie un objet JavaScript simple (typé ) Word.Interfaces.RangeDataqui contient des copies superficielles de toutes les propriétés enfants chargées à partir de l’objet d’origine.

toJSON(): Word.Interfaces.RangeData;

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 entre 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 suivis lors de la création initiale de l’objet. Si cet objet fait partie d’une collection, vous devez également suivre la collection parente.

track(): Word.Range;

Retours

untrack()

Publication mémoire associée à cet objet si elle a été précédemment suivie. Cet appel est l’abréviation de 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 libération de mémoire prenne effet.

untrack(): Word.Range;

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

Jeu d’API : WordApi BÊTA (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

Jeu d’API : WordApi BÊTA (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

Jeu d’API : WordApi BÊTA (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

Jeu d’API : WordApi BÊTA (PRÉVERSION UNIQUEMENT)