Word.Section class
Representa una sección de un documento de Word.
- Extends
Comentarios
Usada por
- Word. Body: parentSection, parentSectionOrNullObject
- Word. SectionCollection: getFirst, getFirstOrNullObject, items
Ejemplos
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/insert-section-breaks.yaml
// Gets the first section and reads the text in its body.
await Word.run(async (context) => {
const sections: Word.SectionCollection = context.document.sections;
const firstSection: Word.Section = sections.getFirst();
const firstSectionBody: Word.Body = firstSection.body;
firstSectionBody.load("text");
await context.sync();
console.log(`First section text: ${firstSectionBody.text}`);
});
Propiedades
| body | Obtiene el |
| borders | Devuelve un |
| context | El contexto de solicitud asociado al objeto. De esta forma, se conecta el proceso del complemento con el proceso de la aplicación host de Office. |
| page |
Devuelve un |
| protected |
Especifica si la sección está protegida para formularios. |
Métodos
| get |
Obtiene uno de los pies de página de la sección. |
| get |
Obtiene uno de los pies de página de la sección. |
| get |
Obtiene uno de los encabezados de la sección. |
| get |
Obtiene uno de los encabezados de la sección. |
| get |
Obtiene la próxima sección. Genera un |
| get |
Obtiene la próxima sección. Si esta sección es la última, este método devolverá un objeto con su |
| load(options) | Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a |
| load(property |
Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a |
| load(property |
Pone en cola un comando para cargar las propiedades especificadas del objeto. Debe llamar a |
| 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 API del mismo tipo. |
| set(properties) | Establece varias propiedades en el objeto al mismo tiempo, basadas en un objeto cargado existente. |
| toJSON() | Reemplaza el método JavaScript |
| track() | Realiza un seguimiento del objeto de ajuste automático según cambios adyacentes en el documento. Esta llamada es una abreviatura de context.trackedObjects.add(thisObject). Si usa este objeto entre |
| untrack() | Libere la memoria asociada a este objeto, si se ha realizado un seguimiento de él anteriormente. Esta llamada es la abreviatura de 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. Deberá llamar |
Detalles de las propiedades
body
Obtiene el Body objeto de la sección. Esto no incluye el encabezado, el pie de página ni otros metadatos de la sección.
readonly body: Word.Body;
Valor de propiedad
Comentarios
Ejemplos
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/insert-section-breaks.yaml
// Gets the body of the second section and reads its text.
await Word.run(async (context) => {
const sections: Word.SectionCollection = context.document.sections;
sections.load("items");
await context.sync();
const secondSection: Word.Section = sections.items[1];
const secondSectionBody: Word.Body = secondSection.body;
secondSectionBody.load("text");
await context.sync();
console.log(`Second section text: ${secondSectionBody.text}`);
});
borders
Devuelve un BorderUniversalCollection objeto que representa todos los bordes de la sección.
readonly borders: Word.BorderUniversalCollection;
Valor de propiedad
Comentarios
Conjunto de API: WordApiDesktop 1.3
Ejemplos
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-section-starts.yaml
// Applies a double blue page border to every section in the report.
await Word.run(async (context) => {
const sections: Word.SectionCollection = context.document.sections;
const firstSection: Word.Section = sections.getFirst();
const sectionBorders: Word.BorderUniversalCollection = firstSection.borders;
sectionBorders.load("items");
await context.sync();
sectionBorders.items.forEach((sectionBorder: Word.BorderUniversal) => {
sectionBorder.isVisible = true;
sectionBorder.color = "#4472C4";
sectionBorder.lineStyle = Word.BorderLineStyle.double;
sectionBorder.lineWidth = Word.LineWidth.pt150;
});
sectionBorders.applyPageBordersToAllSections();
await context.sync();
console.log("Applied page borders to every section.");
});
context
El contexto de solicitud asociado al objeto. De esta forma, se conecta el proceso del complemento con el proceso de la aplicación host de Office.
context: RequestContext;
Valor de propiedad
pageSetup
Devuelve un PageSetup objeto asociado a la sección.
readonly pageSetup: Word.PageSetup;
Valor de propiedad
Comentarios
Conjunto de API: WordApiDesktop 1.3
Ejemplos
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-section-starts.yaml
await Word.run(async (context) => {
// Configure document-wide page settings for a report that will be printed and bound.
const pageSetup: Word.PageSetup = context.document.pageSetup;
pageSetup.set({
paperSize: Word.PaperSize.letter,
orientation: Word.PageOrientation.portrait,
topMargin: 72,
bottomMargin: 72,
leftMargin: 90,
rightMargin: 72,
gutter: 18,
gutterPosition: Word.GutterPosition.left,
mirrorMargins: true,
oddAndEvenPagesHeaderFooter: true
});
const sections: Word.SectionCollection = context.document.sections;
sections.load("items");
await context.sync();
// Start the main chapter on an odd-numbered page so it appears on the right in a bound document.
const chapterPageSetup: Word.PageSetup = sections.items[1].pageSetup;
chapterPageSetup.sectionStart = Word.SectionStart.oddPage;
chapterPageSetup.differentFirstPageHeaderFooter = true;
// Keep the appendix in a separate section, but let it begin on the current page.
sections.items[2].pageSetup.sectionStart = Word.SectionStart.continuous;
await context.sync();
console.log("Applied print and binding settings to the report.");
});
protectedForForms
Especifica si la sección está protegida para formularios.
protectedForForms: boolean;
Valor de propiedad
boolean
Comentarios
Conjunto de API: WordApiDesktop 1.3
Ejemplos
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-section-starts.yaml
// Protects the main chapter section when document form protection is enabled.
await Word.run(async (context) => {
const sections: Word.SectionCollection = context.document.sections;
sections.load("items");
await context.sync();
const chapterSection: Word.Section = sections.items[1];
chapterSection.protectedForForms = true;
await context.sync();
console.log("Marked the main chapter section for form protection.");
});
Detalles del método
getFooter(type)
Obtiene uno de los pies de página de la sección.
getFooter(type: Word.HeaderFooterType): Word.Body;
Parámetros
Tipo de pie de página que se va a devolver. Este valor debe ser: primary, firstPageo evenPages.
Devoluciones
Comentarios
Ejemplos
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy sectionsCollection object.
const mySections = context.document.sections;
// Queue a command to load the sections.
mySections.load('body/style');
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
await context.sync();
// Create a proxy object the primary footer of the first section.
// Note that the footer is a body object.
const myFooter = mySections.items[0].getFooter(Word.HeaderFooterType.primary);
// Queue a command to insert text at the end of the footer.
myFooter.insertText("This is a footer.", Word.InsertLocation.end);
// Queue a command to wrap the header in a content control.
myFooter.insertContentControl();
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
await context.sync();
console.log("Added a footer to the first section.");
});
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/insert-header-and-footer.yaml
// Inserts a first-page footer by using the HeaderFooterType enum.
await Word.run(async (context) => {
const sections: Word.SectionCollection = context.document.sections;
const firstSection: Word.Section = sections.getFirst();
const footerType: Word.HeaderFooterType = Word.HeaderFooterType.firstPage;
const firstPageFooter: Word.Body = firstSection.getFooter(footerType);
firstPageFooter.insertParagraph("This is a first-page footer.", Word.InsertLocation.end);
await context.sync();
});
getFooter(type)
Obtiene uno de los pies de página de la sección.
getFooter(type: "Primary" | "FirstPage" | "EvenPages"): Word.Body;
Parámetros
- type
-
"Primary" | "FirstPage" | "EvenPages"
Tipo de pie de página que se va a devolver. Este valor debe ser: primary, firstPageo evenPages.
Devoluciones
Comentarios
Ejemplos
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/insert-header-and-footer.yaml
// Inserts a primary footer by using the string overload.
await Word.run(async (context) => {
const sections: Word.SectionCollection = context.document.sections;
const firstSection: Word.Section = sections.getFirst();
const primaryFooter: Word.Body = firstSection.getFooter("Primary");
primaryFooter.insertParagraph("This is a primary footer.", Word.InsertLocation.end);
await context.sync();
});
getHeader(type)
Obtiene uno de los encabezados de la sección.
getHeader(type: Word.HeaderFooterType): Word.Body;
Parámetros
Tipo de encabezado que se va a devolver. Este valor debe ser: primary, firstPageo evenPages.
Devoluciones
Comentarios
Ejemplos
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/insert-header-and-footer.yaml
// Inserts a primary header by using the HeaderFooterType enum.
await Word.run(async (context) => {
const sections: Word.SectionCollection = context.document.sections;
const firstSection: Word.Section = sections.getFirst();
const headerType: Word.HeaderFooterType = Word.HeaderFooterType.primary;
const primaryHeader: Word.Body = firstSection.getHeader(headerType);
primaryHeader.insertParagraph("This is a primary header.", Word.InsertLocation.end);
await context.sync();
});
getHeader(type)
Obtiene uno de los encabezados de la sección.
getHeader(type: "Primary" | "FirstPage" | "EvenPages"): Word.Body;
Parámetros
- type
-
"Primary" | "FirstPage" | "EvenPages"
Tipo de encabezado que se va a devolver. Este valor debe ser: primary, firstPageo evenPages.
Devoluciones
Comentarios
Ejemplos
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
// Create a proxy sectionsCollection object.
const mySections = context.document.sections;
// Queue a command to load the sections.
mySections.load('body/style');
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
await context.sync();
// Create a proxy object the primary header of the first section.
// Note that the header is a body object.
const myHeader = mySections.items[0].getHeader("Primary");
// Queue a command to insert text at the end of the header.
myHeader.insertText("This is a header.", Word.InsertLocation.end);
// Queue a command to wrap the header in a content control.
myHeader.insertContentControl();
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
await context.sync();
console.log("Added a header to the first section.");
});
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/insert-header-and-footer.yaml
// Inserts a first-page header by using the string overload.
await Word.run(async (context) => {
const sections: Word.SectionCollection = context.document.sections;
const firstSection: Word.Section = sections.getFirst();
const firstPageHeader: Word.Body = firstSection.getHeader("FirstPage");
firstPageHeader.insertParagraph("This is a first-page header.", Word.InsertLocation.end);
await context.sync();
});
getNext()
Obtiene la próxima sección. Genera un ItemNotFound error si esta sección es la última.
getNext(): Word.Section;
Devoluciones
Comentarios
Ejemplos
// 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}`);
});
getNextOrNullObject()
Obtiene la próxima sección. Si esta sección es la última, este método devolverá un objeto con su isNullObject propiedad establecida en true. Para obtener más información, vea los métodos y propiedades *OrNullObject.
getNextOrNullObject(): Word.Section;
Devoluciones
Comentarios
Ejemplos
// 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, or a null object if it is the last section.
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.getNextOrNullObject();
nextSection.load("isNullObject, body/text");
await context.sync();
if (nextSection.isNullObject) {
console.log("The document doesn't have another section.");
return;
}
console.log(`Next section text: ${nextSection.body.text}`);
});
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.SectionLoadOptions): Word.Section;
Parámetros
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.Section;
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.Section;
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
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 API del mismo tipo.
set(properties: Interfaces.SectionUpdateData, options?: OfficeExtension.UpdateOptions): void;
Parámetros
- properties
- Word.Interfaces.SectionUpdateData
Un objeto JavaScript con propiedades que están estructuradas isomorfamente a las propiedades del objeto en el 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, basadas en un objeto cargado existente.
set(properties: Word.Section): void;
Parámetros
- properties
- Word.Section
Devoluciones
void
toJSON()
Reemplaza el método JavaScript toJSON() para proporcionar una salida más útil cuando se pasa un objeto API a JSON.stringify(). (JSON.stringify, a su vez, llama al toJSON método del objeto que se le pasa). Mientras que el objeto original Word.Section es un objeto API, el toJSON método devuelve un objeto JavaScript simple (escrito como Word.Interfaces.SectionData) que contiene copias superficiales de cualquier propiedad secundaria cargada del objeto original.
toJSON(): Word.Interfaces.SectionData;
Devoluciones
track()
Realiza un seguimiento del objeto de ajuste automático según cambios adyacentes en el documento. Esta llamada es una abreviatura de context.trackedObjects.add(thisObject). Si usa este objeto entre .sync llamadas y fuera de la ejecución secuencial de un lote ".run" y recibe 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 objeto 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.Section;
Devoluciones
untrack()
Libere la memoria asociada a este objeto, si se ha realizado un seguimiento de él anteriormente. Esta llamada es la abreviatura de 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. Deberá llamar context.sync() antes de que la liberación de memoria surta efecto.
untrack(): Word.Section;