Word.Body class

Steht für den Textkörper eines Dokuments oder Abschnitts.

Extends

Hinweise

[ API-Satz: WordApi 1.1 ]

Eigenschaften

contentControls

Ruft die Auflistung von Rich-Text-Inhaltssteuerelementobjekten im Text ab.

context

Der Anforderungskontext, der dem -Objekt zugeordnet ist. Dadurch wird der Prozess des Add-Ins mit dem Prozess der Office-Hostanwendung verbunden.

font

Ruft das Textformat des Textkörpers ab. Verwenden Sie diese Option zum Abrufen und Festlegen von Schriftartname, Schriftgrad, Farbe und anderen Eigenschaften.

inlinePictures

Ruft die Auflistung von InlinePicture-Objekten im Text ab. Die Auflistung enthält keine unverankerten Bilder.

paragraphs

Ruft die Auflistung von Absatzobjekten im Text ab.

parentContentControl

Ruft das Inhaltssteuerelement ab, das den Textkörper enthält. Löst einen Fehler aus ItemNotFound , wenn kein übergeordnetes Inhaltssteuerelement vorhanden ist.

style

Gibt den Formatvorlagennamen für den Text an. Verwenden Sie diese Eigenschaft für benutzerdefinierte Formatvorlagen und lokalisierte Formatvorlagennamen. Informationen zur Verwendung der integrierten Formatvorlagen, die zwischen Gebietsschemas portabel sind, finden Sie unter der Eigenschaft "styleBuiltIn".

text

Ruft den Textkörper ab. Verwenden Sie die InsertText-Methode zum Einfügen von Text.

Methoden

clear()

Löscht den Inhalt des Body-Objekts. Der Benutzer kann den Rückgängig-Vorgang auf den gelöschten Inhalt durchführen.

getHtml()

Ruft eine HTML-Darstellung des Body-Objekts ab. Wenn sie in einer Webseite oder einem HTML-Viewer gerendert wird, ist die Formatierung eine enge, aber nicht exakte Übereinstimmung mit der Formatierung des Dokuments. Diese Methode gibt nicht genau denselben HTML-Code für dasselbe Dokument auf verschiedenen Plattformen (Windows, Mac, Word im Web usw.) zurück. Wenn Sie genaue Genauigkeit oder plattformübergreifende Konsistenz benötigen, verwenden Body.getOoxml() Und konvertieren Sie den zurückgegebenen XML-Code in HTML.

getOoxml()

Ruft die OOXML (Office Open XML)-Darstellung des Body-Objekts ab.

insertBreak(breakType, insertLocation)

Fügt an der angegebenen Position im Hauptdokument einen Umbruch ein.

insertContentControl(contentControlType)

Umschließt das Body-Objekt mit einem Inhaltssteuerelement.

insertFileFromBase64(base64File, insertLocation)

Fügt in den Textkörper an der angegebenen Position ein Dokument ein.

insertHtml(html, insertLocation)

Fügt an der angegebenen Position HTML-Code ein.

insertOoxml(ooxml, insertLocation)

Fügt an der angegebenen Position OOXML-Code ein.

insertParagraph(paragraphText, insertLocation)

Fügt an der angegebenen Position einen Absatz ein.

insertText(text, insertLocation)

Fügt in den Textkörper an der angegebenen Position Text ein.

load(options)

Stellt einen Befehl zum Laden der angegebenen Eigenschaften des Objekts in die Warteschlange ein. Vor dem Lesen der Eigenschaften müssen Sie "context.sync()" aufrufen.

load(propertyNames)

Stellt einen Befehl zum Laden der angegebenen Eigenschaften des Objekts in die Warteschlange ein. Vor dem Lesen der Eigenschaften müssen Sie "context.sync()" aufrufen.

load(propertyNamesAndPaths)

Stellt einen Befehl zum Laden der angegebenen Eigenschaften des Objekts in die Warteschlange ein. Vor dem Lesen der Eigenschaften müssen Sie "context.sync()" aufrufen.

search(searchText, searchOptions)

Führt eine Suche mit den angegebenen SearchOptions für den Bereich des Body-Objekts aus. Die Suchergebnisse sind eine Sammlung von Bereichsobjekten.

select(selectionMode)

Wählt den Textkörper und navigiert die Word-Benutzeroberfläche an diese Position.

select(selectionModeString)

Wählt den Textkörper und navigiert die Word-Benutzeroberfläche an diese Position.

set(properties, options)

Legt mehrere Eigenschaften eines Objekts gleichzeitig fest. Sie können entweder ein einfaches Objekt mit den entsprechenden Eigenschaften oder ein anderes API-Objekt desselben Typs übergeben.

set(properties)

Legt mehrere Eigenschaften für das -Objekt gleichzeitig fest, basierend auf einem vorhandenen geladenen Objekt.

toJSON()

Überschreibt die JavaScript-Methode toJSON() , um eine nützlichere Ausgabe bereitzustellen, wenn ein API-Objekt an JSON.stringify()übergeben wird. (JSON.stringifyruft wiederum die toJSON -Methode des Objekts auf, das an das Objekt übergeben wird.) Die ursprüngliche Word. Body-Objekt ist ein API-Objekt, die toJSON Methode gibt ein einfaches JavaScript-Objekt (typisiert als Word.Interfaces.BodyData) zurück, das flache Kopien aller geladenen untergeordneten Eigenschaften aus dem ursprünglichen Objekt enthält.

track()

Nachverfolgung des Objekts zwecks automatischer Anpassung auf der Grundlage der umgebenden Änderungen im Dokument. Dieser Aufruf ist eine Kurzform für context.trackedObjects.add(thisObject). Wenn Sie dieses Objekt über .sync Aufrufe hinweg und außerhalb der sequenziellen Ausführung eines ".run"-Batches verwenden und beim Festlegen einer Eigenschaft oder beim Aufrufen einer Methode für das Objekt den Fehler "InvalidObjectPath" erhalten, müssen Sie das Objekt der nachverfolgten Objektauflistung hinzufügen, als das Objekt zum ersten Mal erstellt wurde. Wenn dieses Objekt Teil einer Auflistung ist, sollten Sie auch die übergeordnete Auflistung nachverfolgen.

untrack()

Gibt den diesem Objekt zugewiesenen Arbeitsspeicher frei, wenn das Objekt zuvor nachverfolgt wurde. Dieser Aufruf ist die Kurzform für context.trackedObjects.remove(thisObject). Viele nachverfolgte Objekte verlangsamen die Ausführung der Hostanwendung, also achten Sie darauf, alle hinzugefügten Objekte nach abgeschlossener Verwendung freizugeben. Sie müssen aufrufen context.sync() , bevor die Speicherfreigabe wirksam wird.

Details zur Eigenschaft

contentControls

Ruft die Auflistung von Rich-Text-Inhaltssteuerelementobjekten im Text ab.

readonly contentControls: Word.ContentControlCollection;

Eigenschaftswert

Hinweise

[ API-Satz: WordApi 1.1 ]

context

Der Anforderungskontext, der dem -Objekt zugeordnet ist. Dadurch wird der Prozess des Add-Ins mit dem Prozess der Office-Hostanwendung verbunden.

context: RequestContext;

Eigenschaftswert

font

Ruft das Textformat des Textkörpers ab. Verwenden Sie diese Option zum Abrufen und Festlegen von Schriftartname, Schriftgrad, Farbe und anderen Eigenschaften.

readonly font: Word.Font;

Eigenschaftswert

Hinweise

[ API-Satz: WordApi 1.1 ]

Beispiele

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

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

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

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

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

  console.log(results);
});

inlinePictures

Ruft die Auflistung von InlinePicture-Objekten im Text ab. Die Auflistung enthält keine unverankerten Bilder.

readonly inlinePictures: Word.InlinePictureCollection;

Eigenschaftswert

Hinweise

[ API-Satz: WordApi 1.1 ]

Beispiele

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

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

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

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

paragraphs

Ruft die Auflistung von Absatzobjekten im Text ab.

readonly paragraphs: Word.ParagraphCollection;

Eigenschaftswert

Hinweise

[ API-Satz: WordApi 1.1 ]

Wichtig: Absätze in Tabellen werden für die Anforderungssätze 1.1 und 1.2 nicht zurückgegeben. Ab Anforderungssatz 1.3 werden auch Absätze in Tabellen zurückgegeben.

Beispiele

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

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

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

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

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

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

    allSearchResults.push(correlatedResults);
  }

  await context.sync();

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

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

parentContentControl

Ruft das Inhaltssteuerelement ab, das den Textkörper enthält. Löst einen Fehler aus ItemNotFound , wenn kein übergeordnetes Inhaltssteuerelement vorhanden ist.

readonly parentContentControl: Word.ContentControl;

Eigenschaftswert

Hinweise

[ API-Satz: WordApi 1.1 ]

style

Gibt den Formatvorlagennamen für den Text an. Verwenden Sie diese Eigenschaft für benutzerdefinierte Formatvorlagen und lokalisierte Formatvorlagennamen. Informationen zur Verwendung der integrierten Formatvorlagen, die zwischen Gebietsschemas portabel sind, finden Sie unter der Eigenschaft "styleBuiltIn".

style: string;

Eigenschaftswert

string

Hinweise

[ API-Satz: WordApi 1.1 ]

text

Ruft den Textkörper ab. Verwenden Sie die InsertText-Methode zum Einfügen von Text.

readonly text: string;

Eigenschaftswert

string

Hinweise

[ API-Satz: WordApi 1.1 ]

Beispiele

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

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

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

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

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

Details zur Methode

clear()

Löscht den Inhalt des Body-Objekts. Der Benutzer kann den Rückgängig-Vorgang auf den gelöschten Inhalt durchführen.

clear(): void;

Gibt zurück

void

Hinweise

[ API-Satz: WordApi 1.1 ]

Beispiele

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

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

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

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

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

getHtml()

Ruft eine HTML-Darstellung des Body-Objekts ab. Wenn sie in einer Webseite oder einem HTML-Viewer gerendert wird, ist die Formatierung eine enge, aber nicht exakte Übereinstimmung mit der Formatierung des Dokuments. Diese Methode gibt nicht genau denselben HTML-Code für dasselbe Dokument auf verschiedenen Plattformen (Windows, Mac, Word im Web usw.) zurück. Wenn Sie genaue Genauigkeit oder plattformübergreifende Konsistenz benötigen, verwenden Body.getOoxml() Und konvertieren Sie den zurückgegebenen XML-Code in HTML.

getHtml(): OfficeExtension.ClientResult<string>;

Gibt zurück

Hinweise

[ API-Satz: WordApi 1.1 ]

Beispiele

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

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

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

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

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

getOoxml()

Ruft die OOXML (Office Open XML)-Darstellung des Body-Objekts ab.

getOoxml(): OfficeExtension.ClientResult<string>;

Gibt zurück

Hinweise

[ API-Satz: WordApi 1.1 ]

Beispiele

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

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

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

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

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

insertBreak(breakType, insertLocation)

Fügt an der angegebenen Position im Hauptdokument einen Umbruch ein.

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

Parameter

breakType

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

Erforderlich. Der Typ des zum Textkörper hinzuzufügenden Umbruchs.

insertLocation

start | end | "Start" | "End"

Erforderlich. Der Wert muss "Start" oder "End" sein.

Gibt zurück

void

Hinweise

[ API-Satz: WordApi 1.1 ]

Beispiele

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

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

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

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

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

insertContentControl(contentControlType)

Umschließt das Body-Objekt mit einem Inhaltssteuerelement.

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

Parameter

contentControlType

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

Optional. Inhaltssteuerelementtyp, der eingefügt werden soll. Muss "RichText", "PlainText" oder "CheckBox" sein. Der Standardwert ist "RichText".

Gibt zurück

Hinweise

[ API-Satz: WordApi 1.1 ]

Hinweis: Der contentControlType Parameter wurde in WordApi 1.5 eingeführt. PlainText Unterstützung wurde in WordApi 1.5 hinzugefügt. CheckBox Unterstützung wurde in WordApi 1.7 hinzugefügt.

Beispiele

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

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

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

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

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

insertFileFromBase64(base64File, insertLocation)

Fügt in den Textkörper an der angegebenen Position ein Dokument ein.

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

Parameter

base64File

string

Erforderlich. Der Base64-codierte Inhalt einer .docx Datei.

insertLocation

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

Erforderlich. Der Wert muss "Replace", "Start" oder "End" sein.

Gibt zurück

Hinweise

[ API-Satz: WordApi 1.1 ]

Hinweis: Das Einfügen wird nicht unterstützt, wenn das eingefügte Dokument ein ActiveX-Steuerelement (wahrscheinlich in einem Formularfeld) enthält. Erwägen Sie, ein solches Formularfeld durch ein Inhaltssteuerelement oder eine andere für Ihr Szenario geeignete Option zu ersetzen.

Beispiele

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

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

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

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

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

insertHtml(html, insertLocation)

Fügt an der angegebenen Position HTML-Code ein.

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

Parameter

html

string

Erforderlich. Der in das Dokument einzufügende HTML-Code.

insertLocation

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

Erforderlich. Der Wert muss "Replace", "Start" oder "End" sein.

Gibt zurück

Hinweise

[ API-Satz: WordApi 1.1 ]

Beispiele

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

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

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

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

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

insertOoxml(ooxml, insertLocation)

Fügt an der angegebenen Position OOXML-Code ein.

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

Parameter

ooxml

string

Erforderlich. Der einzufügende OOXML-Code.

insertLocation

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

Erforderlich. Der Wert muss "Replace", "Start" oder "End" sein.

Gibt zurück

Hinweise

[ API-Satz: WordApi 1.1 ]

Beispiele

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

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

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

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

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

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

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

insertParagraph(paragraphText, insertLocation)

Fügt an der angegebenen Position einen Absatz ein.

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

Parameter

paragraphText

string

Erforderlich. Der einzufügende Absatztext.

insertLocation

start | end | "Start" | "End"

Erforderlich. Der Wert muss "Start" oder "End" sein.

Gibt zurück

Hinweise

[ API-Satz: WordApi 1.1 ]

Beispiele

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

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

  await context.sync();
});

insertText(text, insertLocation)

Fügt in den Textkörper an der angegebenen Position Text ein.

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

Parameter

text

string

Erforderlich. Der einzufügende Text.

insertLocation

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

Erforderlich. Der Wert muss "Replace", "Start" oder "End" sein.

Gibt zurück

Hinweise

[ API-Satz: WordApi 1.1 ]

Beispiele

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

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

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

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

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

load(options)

Stellt einen Befehl zum Laden der angegebenen Eigenschaften des Objekts in die Warteschlange ein. Vor dem Lesen der Eigenschaften müssen Sie "context.sync()" aufrufen.

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

Parameter

options
Word.Interfaces.BodyLoadOptions

Stellt Optionen dafür bereit, welche Eigenschaften des -Objekts geladen werden sollen.

Gibt zurück

load(propertyNames)

Stellt einen Befehl zum Laden der angegebenen Eigenschaften des Objekts in die Warteschlange ein. Vor dem Lesen der Eigenschaften müssen Sie "context.sync()" aufrufen.

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

Parameter

propertyNames

string | string[]

Eine durch Trennzeichen getrennte Zeichenfolge oder ein Array von Zeichenfolgen, die die zu ladenden Eigenschaften angeben.

Gibt zurück

load(propertyNamesAndPaths)

Stellt einen Befehl zum Laden der angegebenen Eigenschaften des Objekts in die Warteschlange ein. Vor dem Lesen der Eigenschaften müssen Sie "context.sync()" aufrufen.

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

Parameter

propertyNamesAndPaths

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

propertyNamesAndPaths.select ist eine durch Trennzeichen getrennte Zeichenfolge, die die zu ladenden Eigenschaften angibt, und propertyNamesAndPaths.expand eine durch Trennzeichen getrennte Zeichenfolge, die die zu ladenden Navigationseigenschaften angibt.

Gibt zurück

search(searchText, searchOptions)

Führt eine Suche mit den angegebenen SearchOptions für den Bereich des Body-Objekts aus. Die Suchergebnisse sind eine Sammlung von Bereichsobjekten.

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

Parameter

searchText

string

Erforderlich. Der Suchtext. Darf maximal 255 Zeichen lang sein.

searchOptions

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

Optional. Optionen für die Suche.

Gibt zurück

Hinweise

[ API-Satz: WordApi 1.1 ]

Beispiele

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

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

  await context.sync();

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

  await context.sync();
});

...

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

  await context.sync();

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

  await context.sync();
});

select(selectionMode)

Wählt den Textkörper und navigiert die Word-Benutzeroberfläche an diese Position.

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

Parameter

selectionMode
Word.SelectionMode

Optional. Der Auswahlmodus muss "Select", "Start" oder "End" sein. „Select“ ist die Standardeinstellung.

Gibt zurück

void

Hinweise

[ API-Satz: WordApi 1.1 ]

Beispiele

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

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

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

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

select(selectionModeString)

Wählt den Textkörper und navigiert die Word-Benutzeroberfläche an diese Position.

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

Parameter

selectionModeString

"Select" | "Start" | "End"

Optional. Der Auswahlmodus muss "Select", "Start" oder "End" sein. „Select“ ist die Standardeinstellung.

Gibt zurück

void

Hinweise

[ API-Satz: WordApi 1.1 ]

set(properties, options)

Legt mehrere Eigenschaften eines Objekts gleichzeitig fest. Sie können entweder ein einfaches Objekt mit den entsprechenden Eigenschaften oder ein anderes API-Objekt desselben Typs übergeben.

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

Parameter

properties
Word.Interfaces.BodyUpdateData

Ein JavaScript-Objekt mit Eigenschaften, die isomorph zu den Eigenschaften des Objekts strukturiert sind, für das die Methode aufgerufen wird.

options
OfficeExtension.UpdateOptions

Stellt eine Option zum Unterdrücken von Fehlern bereit, wenn das Eigenschaftenobjekt versucht, schreibgeschützte Eigenschaften festzulegen.

Gibt zurück

void

set(properties)

Legt mehrere Eigenschaften für das -Objekt gleichzeitig fest, basierend auf einem vorhandenen geladenen Objekt.

set(properties: Word.Body): void;

Parameter

properties
Word.Body

Gibt zurück

void

toJSON()

Überschreibt die JavaScript-Methode toJSON() , um eine nützlichere Ausgabe bereitzustellen, wenn ein API-Objekt an JSON.stringify()übergeben wird. (JSON.stringifyruft wiederum die toJSON -Methode des Objekts auf, das an das Objekt übergeben wird.) Die ursprüngliche Word. Body-Objekt ist ein API-Objekt, die toJSON Methode gibt ein einfaches JavaScript-Objekt (typisiert als Word.Interfaces.BodyData) zurück, das flache Kopien aller geladenen untergeordneten Eigenschaften aus dem ursprünglichen Objekt enthält.

toJSON(): Word.Interfaces.BodyData;

Gibt zurück

track()

Nachverfolgung des Objekts zwecks automatischer Anpassung auf der Grundlage der umgebenden Änderungen im Dokument. Dieser Aufruf ist eine Kurzform für context.trackedObjects.add(thisObject). Wenn Sie dieses Objekt über .sync Aufrufe hinweg und außerhalb der sequenziellen Ausführung eines ".run"-Batches verwenden und beim Festlegen einer Eigenschaft oder beim Aufrufen einer Methode für das Objekt den Fehler "InvalidObjectPath" erhalten, müssen Sie das Objekt der nachverfolgten Objektauflistung hinzufügen, als das Objekt zum ersten Mal erstellt wurde. Wenn dieses Objekt Teil einer Auflistung ist, sollten Sie auch die übergeordnete Auflistung nachverfolgen.

track(): Word.Body;

Gibt zurück

untrack()

Gibt den diesem Objekt zugewiesenen Arbeitsspeicher frei, wenn das Objekt zuvor nachverfolgt wurde. Dieser Aufruf ist die Kurzform für context.trackedObjects.remove(thisObject). Viele nachverfolgte Objekte verlangsamen die Ausführung der Hostanwendung, also achten Sie darauf, alle hinzugefügten Objekte nach abgeschlossener Verwendung freizugeben. Sie müssen aufrufen context.sync() , bevor die Speicherfreigabe wirksam wird.

untrack(): Word.Body;

Gibt zurück