Word.Body class

Representa el cuerpo de un documento o una sección.

Extends

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Propiedades

contentControls

Obtiene la colección de objetos de control de contenido de texto enriquecido en el cuerpo.

context

Contexto de solicitud asociado al objeto . Esto conecta el proceso del complemento al proceso de la aplicación host de Office.

endnotes

Obtiene la colección de notas al final del cuerpo.

fields

Obtiene la colección de objetos de campo en el cuerpo.

font

Obtiene el formato de texto del cuerpo. Use esta opción para obtener y establecer el nombre de fuente, el tamaño, el color y otras propiedades.

footnotes

Obtiene la colección de notas al pie del cuerpo.

inlinePictures

Obtiene la colección de objetos InlinePicture en el cuerpo. La colección no incluye imágenes flotantes.

lists

Obtiene la colección de objetos de lista en el cuerpo.

paragraphs

Obtiene la colección de objetos de párrafo en el cuerpo.

parentBody

Obtiene el cuerpo primario del cuerpo. Por ejemplo, un cuerpo primario de un cuerpo de celda de tabla podría ser un encabezado. Produce un ItemNotFound error si no hay un cuerpo primario.

parentBodyOrNullObject

Obtiene el cuerpo primario del cuerpo. Por ejemplo, un cuerpo primario de un cuerpo de celda de tabla podría ser un encabezado. Si no hay un cuerpo primario, este método devolverá un objeto con su isNullObject propiedad establecida en true. Para obtener más información, vea *OrNullObject methods and properties( Métodos y propiedades de *OrNullObject).

parentContentControl

Obtiene el control de contenido que contiene el cuerpo. Produce un ItemNotFound error si no hay un control de contenido primario.

parentContentControlOrNullObject

Obtiene el control de contenido que contiene el cuerpo. Si no hay un control de contenido primario, este método devolverá un objeto con su isNullObject propiedad establecida en true. Para obtener más información, vea *OrNullObject methods and properties( Métodos y propiedades de *OrNullObject).

parentSection

Obtiene la sección primaria del cuerpo. Produce un ItemNotFound error si no hay una sección primaria.

parentSectionOrNullObject

Obtiene la sección primaria del cuerpo. Si no hay una sección primaria, este método devolverá un objeto con su isNullObject propiedad establecida en true. Para obtener más información, vea *OrNullObject methods and properties( Métodos y propiedades de *OrNullObject).

style

Especifica el nombre de estilo del cuerpo. Use esta propiedad para los estilos personalizados y los nombres de estilo localizados. Para usar los estilos integrados portátiles entre configuraciones regionales, consulte la propiedad "styleBuiltIn".

styleBuiltIn

Especifica el nombre de estilo integrado para el cuerpo. Use esta propiedad para los estilos integrados que son portátiles entre configuraciones regionales. Para usar estilos personalizados o nombres de estilo localizados, consulte la propiedad "style".

tables

Obtiene la colección de objetos de tabla en el cuerpo.

text

Obtiene el texto del cuerpo. Use el método insertText para insertar texto.

type

Obtiene el tipo del cuerpo. El tipo puede ser 'MainDoc', 'Section', 'Header', 'Footer' o 'TableCell'. Los tipos adicionales "Footnote", "Endnote" y "NoteItem" se admiten en WordAPIOnline 1.1 y versiones posteriores.

Métodos

clear()

Borra el contenido del objeto de cuerpo. El usuario puede realizar la operación de deshacer en el contenido borrado.

getComments()

Obtiene los comentarios asociados al cuerpo.

getContentControls(options)

Obtiene los controles de contenido admitidos actualmente en el cuerpo.

getHtml()

Obtiene una representación HTML del objeto body. Cuando se representa en una página web o un visor HTML, el formato será una coincidencia cercana, pero no exacta, del formato del documento. Este método no devuelve exactamente el mismo HTML para el mismo documento en distintas plataformas (Windows, Mac, Word en la web, etc.). Si necesita fidelidad exacta o coherencia entre plataformas, use Body.getOoxml() y convierta el XML devuelto en HTML.

getOoxml()

Obtiene la representación OOXML (Office Open XML) del objeto de cuerpo.

getRange(rangeLocation)

Obtiene el cuerpo completo, o el punto de inicio o fin del cuerpo, como un intervalo.

getReviewedText(changeTrackingVersion)

Obtiene texto revisado en función de la selección de ChangeTrackingVersion.

getReviewedText(changeTrackingVersionString)

Obtiene texto revisado en función de la selección de ChangeTrackingVersion.

getTrackedChanges()

Obtiene la colección de los objetos TrackedChange en el cuerpo.

insertBreak(breakType, insertLocation)

Inserta un salto en la ubicación especificada del documento principal.

insertContentControl(contentControlType)

Ajusta el objeto Body con un control de contenido.

insertFileFromBase64(base64File, insertLocation)

Inserta un documento en el cuerpo en la ubicación especificada.

insertHtml(html, insertLocation)

Inserta HTML en la ubicación especificada.

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserta una imagen en el cuerpo en la ubicación especificada.

insertOoxml(ooxml, insertLocation)

Inserta OOXML en la ubicación especificada.

insertParagraph(paragraphText, insertLocation)

Inserta un párrafo en la ubicación especificada.

insertTable(rowCount, columnCount, insertLocation, values)

Inserta una tabla con el número especificado de filas y columnas.

insertText(text, insertLocation)

Inserta texto en el cuerpo en la ubicación especificada.

load(options)

Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a context.sync() antes de leer las propiedades.

load(propertyNames)

Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a context.sync() antes de leer las propiedades.

load(propertyNamesAndPaths)

Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a context.sync() antes de leer las propiedades.

search(searchText, searchOptions)

Realiza una búsqueda con las SearchOptions especificadas en el ámbito del objeto body. Los resultados de la búsqueda son una colección de objetos de intervalo.

select(selectionMode)

Selecciona el cuerpo y se desplaza por la interfaz de usuario de Word hasta él.

select(selectionModeString)

Selecciona el cuerpo y se desplaza por la interfaz de usuario de Word hasta él.

set(properties, options)

Establece varias propiedades de un objeto al mismo tiempo. Puede pasar un objeto sin formato con las propiedades adecuadas u otro objeto de API del mismo tipo.

set(properties)

Establece varias propiedades en el objeto al mismo tiempo, en función de un objeto cargado existente.

toJSON()

Invalida el método JavaScript toJSON() para proporcionar una salida más útil cuando se pasa un objeto de API a JSON.stringify(). (JSON.stringifya su vez, llama al toJSON método del objeto que se le pasa). Mientras que el Word original. El objeto Body es un objeto de API, el toJSON método devuelve un objeto JavaScript sin formato (escrito como Word.Interfaces.BodyData) que contiene copias superficiales de las propiedades secundarias cargadas del objeto original.

track()

Realiza un seguimiento del objeto de ajuste automático según cambios adyacentes en el documento. Esta llamada es una abreviatura para context.trackedObjects.add(thisObject). Si usa este objeto entre .sync llamadas y fuera de la ejecución secuencial de un lote ".run" y obtiene un error "InvalidObjectPath" al establecer una propiedad o invocar un método en el objeto, debe agregar el objeto a la colección de objetos de seguimiento cuando se creó el objeto por primera vez. Si este objeto forma parte de una colección, también debe realizar un seguimiento de la colección primaria.

untrack()

Libere la memoria asociada a este objeto, si se ha realizado un seguimiento de él anteriormente. Esta llamada es abreviada para context.trackedObjects.remove(thisObject). Tener muchos objetos marcados ralentiza la aplicación host, así que debe recordar liberar los objetos que agregue cuando haya terminado con ellos. Tendrá que llamar context.sync() a antes de que la versión de memoria surta efecto.

Detalles de las propiedades

contentControls

Obtiene la colección de objetos de control de contenido de texto enriquecido en el cuerpo.

readonly contentControls: Word.ContentControlCollection;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.1 ]

context

Contexto de solicitud asociado al objeto . Esto conecta el proceso del complemento al proceso de la aplicación host de Office.

context: RequestContext;

Valor de propiedad

endnotes

Obtiene la colección de notas al final del cuerpo.

readonly endnotes: Word.NoteItemCollection;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.5 ]

fields

Obtiene la colección de objetos de campo en el cuerpo.

readonly fields: Word.FieldCollection;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.4 ]

Ejemplos

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

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

  await context.sync();

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

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

font

Obtiene el formato de texto del cuerpo. Use esta opción para obtener y establecer el nombre de fuente, el tamaño, el color y otras propiedades.

readonly font: Word.Font;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Ejemplos

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

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

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

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

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

  console.log(results);
});

footnotes

Obtiene la colección de notas al pie del cuerpo.

readonly footnotes: Word.NoteItemCollection;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.5 ]

Ejemplos

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

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

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

inlinePictures

Obtiene la colección de objetos InlinePicture en el cuerpo. La colección no incluye imágenes flotantes.

readonly inlinePictures: Word.InlinePictureCollection;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Ejemplos

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

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

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

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

lists

Obtiene la colección de objetos de lista en el cuerpo.

readonly lists: Word.ListCollection;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.3 ]

paragraphs

Obtiene la colección de objetos de párrafo en el cuerpo.

readonly paragraphs: Word.ParagraphCollection;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Importante: Los párrafos de las tablas no se devuelven para los conjuntos de requisitos 1.1 y 1.2. A partir del conjunto de requisitos 1.3, también se devuelven los párrafos de las tablas.

Ejemplos

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

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

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

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

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

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

    allSearchResults.push(correlatedResults);
  }

  await context.sync();

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

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

parentBody

Obtiene el cuerpo primario del cuerpo. Por ejemplo, un cuerpo primario de un cuerpo de celda de tabla podría ser un encabezado. Produce un ItemNotFound error si no hay un cuerpo primario.

readonly parentBody: Word.Body;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.3 ]

parentBodyOrNullObject

Obtiene el cuerpo primario del cuerpo. Por ejemplo, un cuerpo primario de un cuerpo de celda de tabla podría ser un encabezado. Si no hay un cuerpo primario, este método devolverá un objeto con su isNullObject propiedad establecida en true. Para obtener más información, vea *OrNullObject methods and properties( Métodos y propiedades de *OrNullObject).

readonly parentBodyOrNullObject: Word.Body;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.3 ]

parentContentControl

Obtiene el control de contenido que contiene el cuerpo. Produce un ItemNotFound error si no hay un control de contenido primario.

readonly parentContentControl: Word.ContentControl;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.1 ]

parentContentControlOrNullObject

Obtiene el control de contenido que contiene el cuerpo. Si no hay un control de contenido primario, este método devolverá un objeto con su isNullObject propiedad establecida en true. Para obtener más información, vea *OrNullObject methods and properties( Métodos y propiedades de *OrNullObject).

readonly parentContentControlOrNullObject: Word.ContentControl;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.3 ]

parentSection

Obtiene la sección primaria del cuerpo. Produce un ItemNotFound error si no hay una sección primaria.

readonly parentSection: Word.Section;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.3 ]

parentSectionOrNullObject

Obtiene la sección primaria del cuerpo. Si no hay una sección primaria, este método devolverá un objeto con su isNullObject propiedad establecida en true. Para obtener más información, vea *OrNullObject methods and properties( Métodos y propiedades de *OrNullObject).

readonly parentSectionOrNullObject: Word.Section;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.3 ]

style

Especifica el nombre de estilo del cuerpo. Use esta propiedad para los estilos personalizados y los nombres de estilo localizados. Para usar los estilos integrados portátiles entre configuraciones regionales, consulte la propiedad "styleBuiltIn".

style: string;

Valor de propiedad

string

Comentarios

[ Conjunto de API: WordApi 1.1 ]

styleBuiltIn

Especifica el nombre de estilo integrado para el cuerpo. Use esta propiedad para los estilos integrados que son portátiles entre configuraciones regionales. Para usar estilos personalizados o nombres de estilo localizados, consulte la propiedad "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";

Valor de propiedad

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"

Comentarios

[ Conjunto de API: WordApi 1.3 ]

tables

Obtiene la colección de objetos de tabla en el cuerpo.

readonly tables: Word.TableCollection;

Valor de propiedad

Comentarios

[ Conjunto de API: WordApi 1.3 ]

Ejemplos

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

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

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

text

Obtiene el texto del cuerpo. Use el método insertText para insertar texto.

readonly text: string;

Valor de propiedad

string

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Ejemplos

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

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

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

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

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

type

Obtiene el tipo del cuerpo. El tipo puede ser 'MainDoc', 'Section', 'Header', 'Footer' o 'TableCell'. Los tipos adicionales "Footnote", "Endnote" y "NoteItem" se admiten en WordAPIOnline 1.1 y versiones posteriores.

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

Valor de propiedad

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

Comentarios

[ Conjunto de API: WordApi 1.3 ]

Ejemplos

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

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

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

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

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

Detalles del método

clear()

Borra el contenido del objeto de cuerpo. El usuario puede realizar la operación de deshacer en el contenido borrado.

clear(): void;

Devoluciones

void

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Ejemplos

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

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

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

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

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

getComments()

Obtiene los comentarios asociados al cuerpo.

getComments(): Word.CommentCollection;

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.4 ]

Ejemplos

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

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

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

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

getContentControls(options)

Obtiene los controles de contenido admitidos actualmente en el cuerpo.

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

Parámetros

options
Word.ContentControlOptions

Opcional. Opciones que definen qué controles de contenido se devuelven.

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.5 ]

Importante: Si se proporcionan tipos específicos en el parámetro options, solo se devuelven los controles de contenido de los tipos admitidos. Tenga en cuenta que se iniciará una excepción en el uso de métodos de un Word genérico. ContentControl que no son relevantes para el tipo específico. Con el tiempo, se pueden admitir tipos adicionales de controles de contenido. Por lo tanto, el complemento debe solicitar y controlar tipos específicos de controles de contenido.

getHtml()

Obtiene una representación HTML del objeto body. Cuando se representa en una página web o un visor HTML, el formato será una coincidencia cercana, pero no exacta, del formato del documento. Este método no devuelve exactamente el mismo HTML para el mismo documento en distintas plataformas (Windows, Mac, Word en la web, etc.). Si necesita fidelidad exacta o coherencia entre plataformas, use Body.getOoxml() y convierta el XML devuelto en HTML.

getHtml(): OfficeExtension.ClientResult<string>;

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Ejemplos

// 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()

Obtiene la representación OOXML (Office Open XML) del objeto de cuerpo.

getOoxml(): OfficeExtension.ClientResult<string>;

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Ejemplos

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

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

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

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

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

getRange(rangeLocation)

Obtiene el cuerpo completo, o el punto de inicio o fin del cuerpo, como un intervalo.

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

Parámetros

rangeLocation

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

Opcional. La ubicación del intervalo debe ser "Whole", "Start", "End", "After" o "Content".

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.3 ]

getReviewedText(changeTrackingVersion)

Obtiene texto revisado en función de la selección de ChangeTrackingVersion.

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

Parámetros

changeTrackingVersion
Word.ChangeTrackingVersion

Opcional. El valor debe ser "Original" o "Current". El valor predeterminado es "Current".

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.4 ]

getReviewedText(changeTrackingVersionString)

Obtiene texto revisado en función de la selección de ChangeTrackingVersion.

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

Parámetros

changeTrackingVersionString

"Original" | "Current"

Opcional. El valor debe ser "Original" o "Current". El valor predeterminado es "Current".

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.4 ]

getTrackedChanges()

Obtiene la colección de los objetos TrackedChange en el cuerpo.

getTrackedChanges(): Word.TrackedChangeCollection;

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.6 ]

Ejemplos

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

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

  console.log(trackedChanges);
});

insertBreak(breakType, insertLocation)

Inserta un salto en la ubicación especificada del documento principal.

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

Parámetros

breakType

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

Obligatorio. Tipo de salto que se va a agregar al cuerpo.

insertLocation

start | end | "Start" | "End"

Obligatorio. El valor debe ser "Start" o "End".

Devoluciones

void

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Ejemplos

// 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)

Ajusta el objeto Body con un control de contenido.

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

Parámetros

contentControlType

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

Opcional. Tipo de control de contenido que se va a insertar. Debe ser "RichText", "PlainText" o "CheckBox". El valor predeterminado es "RichText".

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Nota: El contentControlType parámetro se introdujo en WordApi 1.5. PlainText se agregó compatibilidad en WordApi 1.5. CheckBox se agregó compatibilidad en WordApi 1.7.

Ejemplos

// 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)

Inserta un documento en el cuerpo en la ubicación especificada.

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

Parámetros

base64File

string

Obligatorio. Contenido codificado en Base64 de un archivo .docx.

insertLocation

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

Obligatorio. El valor debe ser "Replace", "Start" o "End".

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Nota: La inserción no se admite si el documento que se está insertando contiene un control ActiveX (probablemente en un campo de formulario). Considere la posibilidad de reemplazar este tipo de campo de formulario por un control de contenido u otra opción adecuada para su escenario.

Ejemplos

// 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)

Inserta HTML en la ubicación especificada.

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

Parámetros

html

string

Obligatorio. HTML que se va a insertar en el documento.

insertLocation

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

Obligatorio. El valor debe ser "Replace", "Start" o "End".

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Ejemplos

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

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

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

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

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

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserta una imagen en el cuerpo en la ubicación especificada.

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

Parámetros

base64EncodedImage

string

Obligatorio. Imagen codificada en Base64 que se va a insertar en el cuerpo.

insertLocation

start | end | "Start" | "End"

Obligatorio. El valor debe ser "Start" o "End".

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.2 ]

Ejemplos

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

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

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

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

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

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

insertOoxml(ooxml, insertLocation)

Inserta OOXML en la ubicación especificada.

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

Parámetros

ooxml

string

Obligatorio. OOXML que se va a insertar.

insertLocation

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

Obligatorio. El valor debe ser "Replace", "Start" o "End".

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Ejemplos

// 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)

Inserta un párrafo en la ubicación especificada.

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

Parámetros

paragraphText

string

Obligatorio. Texto de párrafo que se va a insertar.

insertLocation

start | end | "Start" | "End"

Obligatorio. El valor debe ser "Start" o "End".

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Ejemplos

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

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

  await context.sync();
});

insertTable(rowCount, columnCount, insertLocation, values)

Inserta una tabla con el número especificado de filas y columnas.

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

Parámetros

rowCount

number

Obligatorio. Número de filas de la tabla.

columnCount

number

Obligatorio. Número de columnas de la tabla.

insertLocation

start | end | "Start" | "End"

Obligatorio. El valor debe ser "Start" o "End".

values

string[][]

Matriz 2D opcional. Si se especifican las cadenas correspondientes en la matriz, se rellenan las celdas.

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.3 ]

Ejemplos

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

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

  await context.sync();
});

insertText(text, insertLocation)

Inserta texto en el cuerpo en la ubicación especificada.

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

Parámetros

text

string

Obligatorio. Texto que se va a insertar.

insertLocation

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

Obligatorio. El valor debe ser "Replace", "Start" o "End".

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Ejemplos

// 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)

Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a context.sync() antes de leer las propiedades.

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

Parámetros

options
Word.Interfaces.BodyLoadOptions

Proporciona opciones para las propiedades del objeto que se van a cargar.

Devoluciones

load(propertyNames)

Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a context.sync() antes de leer las propiedades.

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

Parámetros

propertyNames

string | string[]

Una cadena delimitada por comas o una matriz de cadenas que especifican las propiedades que se van a cargar.

Devoluciones

load(propertyNamesAndPaths)

Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a context.sync() antes de leer las propiedades.

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

Parámetros

propertyNamesAndPaths

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

propertyNamesAndPaths.select es una cadena delimitada por comas que especifica las propiedades que se van a cargar y propertyNamesAndPaths.expand es una cadena delimitada por comas que especifica las propiedades de navegación que se van a cargar.

Devoluciones

search(searchText, searchOptions)

Realiza una búsqueda con las SearchOptions especificadas en el ámbito del objeto body. Los resultados de la búsqueda son una colección de objetos de intervalo.

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

Parámetros

searchText

string

Obligatorio. Texto de búsqueda. Puede tener un máximo de 255 caracteres.

searchOptions

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

Opcional. Opciones de la búsqueda.

Devoluciones

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Ejemplos

// 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)

Selecciona el cuerpo y se desplaza por la interfaz de usuario de Word hasta él.

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

Parámetros

selectionMode
Word.SelectionMode

Opcional. El modo de selección debe ser "Seleccionar", "Iniciar" o "Finalizar". 'Select' es el valor predeterminado.

Devoluciones

void

Comentarios

[ Conjunto de API: WordApi 1.1 ]

Ejemplos

// 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)

Selecciona el cuerpo y se desplaza por la interfaz de usuario de Word hasta él.

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

Parámetros

selectionModeString

"Select" | "Start" | "End"

Opcional. El modo de selección debe ser "Seleccionar", "Iniciar" o "Finalizar". 'Select' es el valor predeterminado.

Devoluciones

void

Comentarios

[ Conjunto de API: WordApi 1.1 ]

set(properties, options)

Establece varias propiedades de un objeto al mismo tiempo. Puede pasar un objeto sin formato con las propiedades adecuadas u otro objeto de API del mismo tipo.

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

Parámetros

properties
Word.Interfaces.BodyUpdateData

Objeto JavaScript con propiedades estructuradas isomórficamente con las propiedades del objeto al que se llama al método.

options
OfficeExtension.UpdateOptions

Proporciona una opción para suprimir errores si el objeto properties intenta establecer propiedades de solo lectura.

Devoluciones

void

set(properties)

Establece varias propiedades en el objeto al mismo tiempo, en función de un objeto cargado existente.

set(properties: Word.Body): void;

Parámetros

properties
Word.Body

Devoluciones

void

toJSON()

Invalida el método JavaScript toJSON() para proporcionar una salida más útil cuando se pasa un objeto de API a JSON.stringify(). (JSON.stringifya su vez, llama al toJSON método del objeto que se le pasa). Mientras que el Word original. El objeto Body es un objeto de API, el toJSON método devuelve un objeto JavaScript sin formato (escrito como Word.Interfaces.BodyData) que contiene copias superficiales de las propiedades secundarias cargadas del objeto original.

toJSON(): Word.Interfaces.BodyData;

Devoluciones

track()

Realiza un seguimiento del objeto de ajuste automático según cambios adyacentes en el documento. Esta llamada es una abreviatura para context.trackedObjects.add(thisObject). Si usa este objeto entre .sync llamadas y fuera de la ejecución secuencial de un lote ".run" y obtiene un error "InvalidObjectPath" al establecer una propiedad o invocar un método en el objeto, debe agregar el objeto a la colección de objetos de seguimiento cuando se creó el objeto por primera vez. Si este objeto forma parte de una colección, también debe realizar un seguimiento de la colección primaria.

track(): Word.Body;

Devoluciones

untrack()

Libere la memoria asociada a este objeto, si se ha realizado un seguimiento de él anteriormente. Esta llamada es abreviada para context.trackedObjects.remove(thisObject). Tener muchos objetos marcados ralentiza la aplicación host, así que debe recordar liberar los objetos que agregue cuando haya terminado con ellos. Tendrá que llamar context.sync() a antes de que la versión de memoria surta efecto.

untrack(): Word.Body;

Devoluciones