Configuraciones de Alineación
Configurando Ajustes de Alineación
Configuraciones de Alineación en Microsoft Excel
Cualquiera que haya usado Microsoft Excel para formatear celdas estará familiarizado con las configuraciones de alineación en Microsoft Excel.
Como puedes ver en la figura anterior, hay diferentes tipos de opciones de alineación:
- Alineación de texto (horizontal y vertical)
- Sangría
- Orientación.
- Control de texto.
- Dirección del texto.
Todos estos ajustes de alineación son completamente compatibles con Aspose.Cells y se discuten con más detalle a continuación.
Ajustes de alineación en Aspose.Cells
Aspose.Cells proporciona una clase, Workbook, que representa un archivo de Excel. La clase Workbook contiene una colección Worksheets que permite acceder a cada hoja de cálculo en el archivo Excel. Una hoja de cálculo está representada por la clase Worksheet. La clase Worksheet proporciona una colección getCells(). Cada elemento en la colección Cells representa un objeto de la clase Cell.
Aspose.Cells proporciona métodos getStyle y setStyle para la clase Cell que se usan para obtener y establecer el formato de una celda. La clase Style ofrece propiedades útiles para configurar configuraciones de alineación.
Selecciona cualquier tipo de alineación de texto usando la enumeración TextAlignmentType. Los tipos de alineación predefinidos en la enumeración TextAlignmentType son:
Tipos de Alineación de Texto | Descripción |
---|---|
Bottom | Representa la alineación del texto inferior |
Center | Representa la alineación del texto centrado |
CenterAcross | Representa la alineación del texto centrado a través |
Distributed | Representa la alineación del texto distribuido |
Fill | Representa la alineación del texto de relleno |
General | Representa la alineación del texto general |
Justify | Representa la alineación del texto justificado |
Left | Representa la alineación del texto a la izquierda |
Right | Representa la alineación del texto a la derecha |
Top | Representa la alineación del texto superior |
JustifiedLow | Alinea el texto con una longitud de kashida ajustada para el texto árabe. |
ThaiDistributed | Distribuye texto en tailandés especialmente, porque cada carácter se trata como una palabra. |
Alineación horizontal
Usa el método setHorizontalAlignment del objeto Style para alinear el texto horizontalmente.
const path = require("path"); | |
const AsposeCells = require("aspose.cells.node"); | |
// The path to the documents directory. | |
const dataDir = path.join(__dirname, "data"); | |
// Create directory if it is not already present. | |
if (!fs.existsSync(dataDir)) { | |
fs.mkdirSync(dataDir); | |
} | |
// Instantiating a Workbook object | |
const workbook = new AsposeCells.Workbook(); | |
// Obtaining the reference of the worksheet | |
const worksheet = workbook.getWorksheets().get(0); | |
// Accessing the "A1" cell from the worksheet | |
const cell = worksheet.getCells().get("A1"); | |
// Adding some value to the "A1" cell | |
cell.putValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
const style = cell.getStyle(); | |
style.setHorizontalAlignment(AsposeCells.TextAlignmentType.Center); | |
cell.setStyle(style); | |
// Saving the Excel file | |
workbook.save(path.join(dataDir, "book1.out.xls"), AsposeCells.SaveFormat.Excel97To2003); |
Alineación vertical
De manera similar a la alineación horizontal, usa el método setVerticalAlignment del objeto Style para alinear el texto verticalmente.
const path = require("path"); | |
const AsposeCells = require("aspose.cells.node"); | |
// The path to the documents directory. | |
const dataDir = path.join(__dirname, "data"); | |
// Create directory if it is not already present. | |
if (!require("fs").existsSync(dataDir)) { | |
require("fs").mkdirSync(dataDir); | |
} | |
// Instantiating a Workbook object | |
const workbook = new AsposeCells.Workbook(); | |
// Clearing all the worksheets | |
workbook.getWorksheets().clear(); | |
// Adding a new worksheet to the Excel object | |
const i = workbook.getWorksheets().add(); | |
// Obtaining the reference of the newly added worksheet by passing its sheet index | |
const worksheet = workbook.getWorksheets().get(i); | |
// Accessing the "A1" cell from the worksheet | |
const cell = worksheet.getCells().get("A1"); | |
// Adding some value to the "A1" cell | |
cell.putValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
const style = cell.getStyle(); | |
// Setting the vertical alignment of the text in a cell | |
style.setVerticalAlignment(AsposeCells.TextAlignmentType.Center); | |
cell.setStyle(style); | |
// Saving the Excel file | |
workbook.save(path.join(dataDir, "book1.out.xls"), AsposeCells.SaveFormat.Excel97To2003); |
Sangría
Es posible establecer el nivel de sangría del texto en una celda con el método setIndentLevel del objeto Style.
const path = require("path"); | |
const AsposeCells = require("aspose.cells.node"); | |
// The path to the documents directory. | |
const dataDir = path.join(__dirname, "data"); | |
// Create directory if it is not already present. | |
if (!require("fs").existsSync(dataDir)) { | |
require("fs").mkdirSync(dataDir); | |
} | |
// Instantiating a Workbook object | |
const workbook = new AsposeCells.Workbook(); | |
// Obtaining the reference of the worksheet | |
const worksheet = workbook.getWorksheets().get(0); | |
// Accessing the "A1" cell from the worksheet | |
const cell = worksheet.getCells().get("A1"); | |
// Adding some value to the "A1" cell | |
cell.putValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
const style = cell.getStyle(); | |
// Setting the indentation level of the text (inside the cell) to 2 | |
style.setIndentLevel(2); | |
cell.setStyle(style); | |
// Saving the Excel file | |
workbook.save(path.join(dataDir, "book1.out.xls"), AsposeCells.SaveFormat.Excel97To2003); |
Orientación
Establece la orientación (rotación) del texto en una celda con el método setRotationAngle del objeto Style.
const path = require("path"); | |
const AsposeCells = require("aspose.cells.node"); | |
// The path to the documents directory. | |
const dataDir = path.join(__dirname, "data"); | |
// Create directory if it is not already present. | |
if (!require("fs").existsSync(dataDir)) { | |
require("fs").mkdirSync(dataDir); | |
} | |
// Instantiating a Workbook object | |
const workbook = new AsposeCells.Workbook(); | |
// Obtaining the reference of the worksheet | |
const worksheet = workbook.getWorksheets().get(0); | |
// Accessing the "A1" cell from the worksheet | |
const cell = worksheet.getCells().get("A1"); | |
// Adding some value to the "A1" cell | |
cell.putValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
const style = cell.getStyle(); | |
// Setting the rotation of the text (inside the cell) to 25 | |
style.setRotationAngle(25); | |
cell.setStyle(style); | |
// Saving the Excel file | |
workbook.save(path.join(dataDir, "book1.out.xls"), AsposeCells.SaveFormat.Excel97To2003); |
Control de texto
La siguiente sección explica cómo controlar el texto mediante el ajuste del ajuste de texto, el ajuste al tamaño y otras opciones de formato.
Envolver texto
Envolver texto en una celda facilita su lectura: la altura de la celda se ajusta para que quepa todo el texto, en lugar de cortarlo o desbordarse a celdas adyacentes. Configura el ajuste de texto activándolo o desactivándolo con el método setIsTextWrapped(boolean) del objeto Style.
const path = require("path"); | |
const AsposeCells = require("aspose.cells.node"); | |
// The path to the documents directory. | |
const dataDir = path.join(__dirname, "data"); | |
// Create Workbook Object | |
const wb = new AsposeCells.Workbook(); | |
// Open first Worksheet in the workbook | |
const ws = wb.getWorksheets().get(0); | |
// Get Worksheet Cells Collection | |
const cell = ws.getCells(); | |
// Increase the width of First Column Width | |
cell.setColumnWidth(0, 35); | |
// Increase the height of first row | |
cell.setRowHeight(0, 36); | |
// Add Text to the First Cell | |
cell.checkCell(0, 0).putValue("I am using the latest version of Aspose.Cells to test this functionality"); | |
// Make Cell's Text wrap | |
const style = cell.checkCell(0, 0).getStyle(); | |
style.setIsTextWrapped(true); | |
cell.checkCell(0, 0).setStyle(style); | |
// Save Excel File | |
wb.save(path.join(dataDir, "WrappingText.out.xlsx")); |
Reducir para ajustar
Una opción para ajustar el texto en un campo es reducir el tamaño del texto para que quepa en las dimensiones de la celda. Esto se hace configurando el método setShrinkToFit(boolean) del objeto Style en verdadero.
const path = require("path"); | |
const AsposeCells = require("aspose.cells.node"); | |
// The path to the documents directory. | |
const dataDir = path.join(__dirname, "data"); | |
// Create directory if it is not already present. | |
if (!require("fs").existsSync(dataDir)) { | |
require("fs").mkdirSync(dataDir); | |
} | |
// Instantiating a Workbook object | |
const workbook = new AsposeCells.Workbook(); | |
// Obtaining the reference of the worksheet | |
const worksheet = workbook.getWorksheets().get(0); | |
// Accessing the "A1" cell from the worksheet | |
const cell = worksheet.getCells().get("A1"); | |
// Adding some value to the "A1" cell | |
cell.putValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
const style = cell.getStyle(); | |
// Shrinking the text to fit according to the dimensions of the cell | |
style.setShrinkToFit(true); | |
cell.setStyle(style); | |
// Saving the Excel file | |
workbook.save(path.join(dataDir, "book1.out.xls"), AsposeCells.SaveFormat.Excel97To2003); |
Combinar celdas
Al igual que Microsoft Excel, Aspose.Cells soporta fusionar varias celdas en una sola. Aspose.Cells ofrece dos enfoques para esta tarea. Uno es llamar al método merge de la colección Cells. El método merge recibe los siguientes parámetros para fusionar las celdas:
- Primera fila: la primera fila desde donde comenzar a combinar.
- Primera columna: la primera columna desde donde comenzar a combinar.
- Número de filas: el número de filas a fusionar.
- Número de columnas: el número de columnas a fusionar.
const path = require("path"); | |
const AsposeCells = require("aspose.cells.node"); | |
// The path to the documents directory. | |
const dataDir = path.join(__dirname, "data"); | |
// Create directory if it is not already present. | |
if (!require("fs").existsSync(dataDir)) { | |
require("fs").mkdirSync(dataDir); | |
} | |
// Create a Workbook. | |
const wbk = new AsposeCells.Workbook(); | |
// Create a Worksheet and get the first sheet. | |
const worksheet = wbk.getWorksheets().get(0); | |
// Create a Cells object to fetch all the cells. | |
const cells = worksheet.getCells(); | |
// Merge some Cells (C6:E7) into a single C6 Cell. | |
cells.merge(5, 2, 2, 3); | |
// Input data into C6 Cell. | |
cells.get(5, 2).putValue("This is my value"); | |
// Create a Style object to fetch the Style of C6 Cell. | |
const style = cells.get(5, 2).getStyle(); | |
// Create a Font object | |
const font = style.getFont(); | |
// Set the name. | |
font.setName("Times New Roman"); | |
// Set the font size. | |
font.setSize(18); | |
// Set the font color | |
font.setColor(AsposeCells.Color.Blue); | |
// Bold the text | |
font.setIsBold(true); | |
// Make it italic | |
font.setIsItalic(true); | |
// Set the background color of C6 Cell to Red | |
style.setForegroundColor(AsposeCells.Color.Red); | |
style.setPattern(AsposeCells.BackgroundType.Solid); | |
// Apply the Style to C6 Cell. | |
cells.get(5, 2).setStyle(style); | |
// Save the Workbook. | |
wbk.save(path.join(dataDir, "mergingcells.out.xls")); |
La otra forma es primero llamar al método createRange de la colección Cells para crear un rango de celdas a fusionar. El método createRange recibe los mismos parámetros que el método merge mencionado arriba y devuelve un objeto Range. El objeto Range también proporciona un método merge que une el rango especificado en el objeto Range.
Dirección del texto
Es posible establecer el orden de lectura del texto en las celdas. El orden de lectura es el orden visual en el que se muestran los caracteres, palabras, etc. Por ejemplo, el inglés es un idioma de izquierda a derecha, mientras que el árabe es un idioma de derecha a izquierda.
El orden de lectura se configura con la propiedad TextDirection del objeto Style. Aspose.Cells proporciona tipos de dirección de texto predefinidos en la enumeración TextDirectionType.
Tipos de dirección de texto | Descripción |
---|---|
Context | El orden de lectura es coherente con el idioma del primer carácter introducido |
LeftToRight | Orden de lectura de izquierda a derecha |
RightToLeft | Orden de lectura de derecha a izquierda |
const path = require("path"); | |
const AsposeCells = require("aspose.cells.node"); | |
// The path to the documents directory. | |
const dataDir = path.join(__dirname, "data"); | |
const filePath = path.join(dataDir, "sample.xlsx"); | |
// Loads the workbook which contains hidden external links | |
const workbook = new AsposeCells.Workbook(filePath); | |
// Instantiating a Workbook object | |
// Obtaining the reference of first worksheet | |
const worksheet = workbook.getWorksheets().get(0); | |
// Accessing the "A1" cell from the worksheet | |
const cell = worksheet.getCells().get("A1"); | |
// Adding some value to the "A1" cell | |
cell.putValue("I am using the latest version of Aspose.Cells to test this functionality."); | |
// Gets style in the "A1" cell | |
const style = cell.getStyle(); | |
// Shrinking the text to fit according to the dimensions of the cell | |
style.setTextDirection(AsposeCells.TextDirectionType.LeftToRight); | |
cell.setStyle(style); | |
// Saving the Excel file | |
workbook.save("book1.xlsx"); |