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 el acceso a cada hoja de cálculo en el archivo de Excel. Una hoja de cálculo está representada por la clase Worksheet. La clase Worksheet proporciona una colección Cells. 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 utilizan para obtener y establecer el formato de una celda. La clase Style proporciona propiedades útiles para configurar los ajustes de alineación.
Seleccione cualquier tipo de alineación de texto utilizando la enumeración TextAlignmentType. Los tipos de alineación de texto 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 la propiedad HorizontalAlignment del objeto Style para alinear el texto horizontalmente.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create directory if it is not already present. | |
bool IsExists = System.IO.Directory.Exists(dataDir); | |
if (!IsExists) | |
System.IO.Directory.CreateDirectory(dataDir); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Obtaining the reference of the worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Accessing the "A1" cell from the worksheet | |
Aspose.Cells.Cell cell = worksheet.Cells["A1"]; | |
// Adding some value to the "A1" cell | |
cell.PutValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
Style style = cell.GetStyle(); | |
style.HorizontalAlignment = TextAlignmentType.Center; | |
cell.SetStyle(style); | |
// Saving the Excel file | |
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); |
Alineación vertical
Similar a la alineación horizontal, usa la propiedad VerticalAlignment del objeto Style para alinear el texto verticalmente.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create directory if it is not already present. | |
bool IsExists = System.IO.Directory.Exists(dataDir); | |
if (!IsExists) | |
System.IO.Directory.CreateDirectory(dataDir); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Clearing all the worksheets | |
workbook.Worksheets.Clear(); | |
// Adding a new worksheet to the Excel object | |
int i = workbook.Worksheets.Add(); | |
// Obtaining the reference of the newly added worksheet by passing its sheet index | |
Worksheet worksheet = workbook.Worksheets[i]; | |
// Accessing the "A1" cell from the worksheet | |
Aspose.Cells.Cell cell = worksheet.Cells["A1"]; | |
// Adding some value to the "A1" cell | |
cell.PutValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
Style style = cell.GetStyle(); | |
// Setting the vertical alignment of the text in a cell | |
style.VerticalAlignment = TextAlignmentType.Center; | |
cell.SetStyle(style); | |
// Saving the Excel file | |
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); |
Sangría
Es posible establecer el nivel de sangría del texto en una celda con la propiedad IndentLevel del objeto Style.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create directory if it is not already present. | |
bool IsExists = System.IO.Directory.Exists(dataDir); | |
if (!IsExists) | |
System.IO.Directory.CreateDirectory(dataDir); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Obtaining the reference of the worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Accessing the "A1" cell from the worksheet | |
Aspose.Cells.Cell cell = worksheet.Cells["A1"]; | |
// Adding some value to the "A1" cell | |
cell.PutValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
Style style = cell.GetStyle(); | |
// Setting the indentation level of the text (inside the cell) to 2 | |
style.IndentLevel = 2; | |
cell.SetStyle(style); | |
// Saving the Excel file | |
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); |
Orientación
Establece la orientación (rotación) del texto en una celda con la propiedad RotationAngle del objeto Style.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create directory if it is not already present. | |
bool IsExists = System.IO.Directory.Exists(dataDir); | |
if (!IsExists) | |
System.IO.Directory.CreateDirectory(dataDir); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Obtaining the reference of the worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Accessing the "A1" cell from the worksheet | |
Aspose.Cells.Cell cell = worksheet.Cells["A1"]; | |
// Adding some value to the "A1" cell | |
cell.PutValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
Style style = cell.GetStyle(); | |
// Setting the rotation of the text (inside the cell) to 25 | |
style.RotationAngle = 25; | |
cell.SetStyle(style); | |
// Saving the Excel file | |
workbook.Save(dataDir + "book1.out.xls", 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 el texto en una celda hace que sea más fácil de leer: la altura de la celda se ajusta para que quepa todo el texto, en lugar de cortarlo o derramarse en celdas adyacentes. Establece el ajuste de texto en on o off con la propiedad IsTextWrapped del objeto Style.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create Workbook Object | |
Workbook wb = new Workbook(); | |
// Open first Worksheet in the workbook | |
Worksheet ws = wb.Worksheets[0]; | |
// Get Worksheet Cells Collection | |
Aspose.Cells.Cells cell = ws.Cells; | |
// 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 Firts Cell | |
cell[0, 0].PutValue("I am using the latest version of Aspose.Cells to test this functionality"); | |
// Make Cell's Text wrap | |
Style style = cell[0, 0].GetStyle(); | |
style.IsTextWrapped = true; | |
cell[0, 0].SetStyle(style); | |
// Save Excel File | |
wb.Save(dataDir+ "WrappingText.out.xlsx"); |
Reducir para ajustar
Una opción para envolver texto en un campo es reducir el tamaño del texto para ajustarse a las dimensiones de una celda. Esto se hace configurando la propiedad IsTextWrapped del objeto Style como true.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create directory if it is not already present. | |
bool IsExists = System.IO.Directory.Exists(dataDir); | |
if (!IsExists) | |
System.IO.Directory.CreateDirectory(dataDir); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Obtaining the reference of the worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Accessing the "A1" cell from the worksheet | |
Aspose.Cells.Cell cell = worksheet.Cells["A1"]; | |
// Adding some value to the "A1" cell | |
cell.PutValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
Style style = cell.GetStyle(); | |
// Shrinking the text to fit according to the dimensions of the cell | |
style.ShrinkToFit = true; | |
cell.SetStyle(style); | |
// Saving the Excel file | |
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); |
Combinar celdas
Al igual que Microsoft Excel, Aspose.Cells admite combinar varias celdas en una. Aspose.Cells proporciona dos enfoques para esta tarea. Una forma es llamar al método Merge de la colección Cells. El método Merge toma los siguientes parámetros para combinar 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.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create directory if it is not already present. | |
bool IsExists = System.IO.Directory.Exists(dataDir); | |
if (!IsExists) | |
System.IO.Directory.CreateDirectory(dataDir); | |
// Create a Workbook. | |
Workbook wbk = new Workbook(); | |
// Create a Worksheet and get the first sheet. | |
Worksheet worksheet = wbk.Worksheets[0]; | |
// Create a Cells object ot fetch all the cells. | |
Cells cells = worksheet.Cells; | |
// Merge some Cells (C6:E7) into a single C6 Cell. | |
cells.Merge(5, 2, 2, 3); | |
// Input data into C6 Cell. | |
worksheet.Cells[5, 2].PutValue("This is my value"); | |
// Create a Style object to fetch the Style of C6 Cell. | |
Style style = worksheet.Cells[5, 2].GetStyle(); | |
// Create a Font object | |
Font font = style.Font; | |
// Set the name. | |
font.Name = "Times New Roman"; | |
// Set the font size. | |
font.Size = 18; | |
// Set the font color | |
font.Color = System.Drawing.Color.Blue; | |
// Bold the text | |
font.IsBold = true; | |
// Make it italic | |
font.IsItalic = true; | |
// Set the backgrond color of C6 Cell to Red | |
style.ForegroundColor = System.Drawing.Color.Red; | |
style.Pattern = BackgroundType.Solid; | |
// Apply the Style to C6 Cell. | |
cells[5, 2].SetStyle(style); | |
// Save the Workbook. | |
wbk.Save(dataDir + "mergingcells.out.xls"); |
La otra forma es llamar primero al método CreateRange de la colección Cells para crear un rango de celdas a fusionar. El método CreateRange toma el mismo conjunto de parámetros que el método Merge discutido anteriormente y devuelve un objeto Range. El objeto Range también proporciona un método Merge que fusiona 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 establece 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 |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Obtaining the reference of first worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Accessing the "A1" cell from the worksheet | |
Cell cell = worksheet.Cells["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 | |
Style style = cell.GetStyle(); | |
// Shrinking the text to fit according to the dimensions of the cell | |
style.TextDirection = (TextDirectionType.LeftToRight); | |
cell.SetStyle(style); | |
// Saving the Excel file | |
workbook.Save("book1.xlsx"); |