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.
Todas estas configuraciones de alineación son totalmente compatibles con Aspose.Cells para Python via .NET y se discuten en más detalle abajo.
Configuraciones de alineación en Aspose.Cells para Python via .NET
Aspose.Cells para Python via .NET 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 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 para Python via .NET proporciona métodos get_style y set_style para la clase Cell que se utilizan para obtener y establecer el formato de una celda. La clase Style proporciona propiedades útiles para configurar configuraciones 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 |
---|---|
GENERAL | Representa alineación de texto general |
BOTTOM | Representa alineación de texto en la parte inferior |
CENTER | Representa alineación de texto en el centro |
CENTER_ACROSS | Representa alineación de texto centrada en atravesar |
DISTRIBUTED | Representa alineación de texto distribuida |
FILL | Representa alineación de texto de relleno |
JUSTIFY | Representa alineación de texto justificada |
LEFT | Representa alineación de texto a la izquierda |
RIGHT | Representa alineación de texto a la derecha |
TOP | Representa alineación de texto en la parte superior |
JUSTIFIED_LOW | Alinea el texto con una longitud de khashida ajustada para texto árabe |
THAI_DISTRIBUTED | Distribuye el texto tailandés de manera especial, ya que cada carácter se trata como una palabra |
Alineación horizontal
Usa la propiedad horizontal_alignment del objeto Style para alinear el texto horizontalmente.
from aspose.cells import SaveFormat, TextAlignmentType, Workbook | |
from os import os, path | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Create directory if it is not already present. | |
IsExists = path.isdir(dataDir) | |
if notIsExists: | |
os.makedirs(dataDir) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the worksheet | |
worksheet = workbook.worksheets[0] | |
# Accessing the "A1" cell from the worksheet | |
cell = worksheet.cells.get("A1") | |
# Adding some value to the "A1" cell | |
cell.put_value("Visit Aspose!") | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style = cell.get_style() | |
style.horizontal_alignment = TextAlignmentType.CENTER | |
cell.set_style(style) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls", SaveFormat.EXCEL_97_TO_2003) |
Alineación vertical
Similar a la alineación horizontal, usa la propiedad vertical_alignment del objeto Style para alinear el texto verticalmente.
from aspose.cells import SaveFormat, TextAlignmentType, Workbook | |
from os import os, path | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Create directory if it is not already present. | |
IsExists = path.isdir(dataDir) | |
if notIsExists: | |
os.makedirs(dataDir) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Clearing all the worksheets | |
workbook.worksheets.clear() | |
# Adding a new worksheet to the Excel object | |
i = workbook.worksheets.add() | |
# Obtaining the reference of the newly added worksheet by passing its sheet index | |
worksheet = workbook.worksheets[i] | |
# Accessing the "A1" cell from the worksheet | |
cell = worksheet.cells.get("A1") | |
# Adding some value to the "A1" cell | |
cell.put_value("Visit Aspose!") | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style = cell.get_style() | |
# Setting the vertical alignment of the text in a cell | |
style.vertical_alignment = TextAlignmentType.CENTER | |
cell.set_style(style) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls", SaveFormat.EXCEL_97_TO_2003) |
Sangría
Es posible establecer el nivel de sangría del texto en una celda con la propiedad indent_level del objeto Style.
from aspose.cells import SaveFormat, Workbook | |
from os import os, path | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Create directory if it is not already present. | |
IsExists = path.isdir(dataDir) | |
if notIsExists: | |
os.makedirs(dataDir) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the worksheet | |
worksheet = workbook.worksheets[0] | |
# Accessing the "A1" cell from the worksheet | |
cell = worksheet.cells.get("A1") | |
# Adding some value to the "A1" cell | |
cell.put_value("Visit Aspose!") | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style = cell.get_style() | |
# Setting the indentation level of the text (inside the cell) to 2 | |
style.indent_level = 2 | |
cell.set_style(style) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls", SaveFormat.EXCEL_97_TO_2003) |
Orientación
Establece la orientación (rotación) del texto en una celda con la propiedad rotation_angle del objeto Style.
from aspose.cells import SaveFormat, Workbook | |
from os import os, path | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Create directory if it is not already present. | |
IsExists = path.isdir(dataDir) | |
if notIsExists: | |
os.makedirs(dataDir) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the worksheet | |
worksheet = workbook.worksheets[0] | |
# Accessing the "A1" cell from the worksheet | |
cell = worksheet.cells.get("A1") | |
# Adding some value to the "A1" cell | |
cell.put_value("Visit Aspose!") | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style = cell.get_style() | |
# Setting the rotation of the text (inside the cell) to 25 | |
style.rotation_angle = 25 | |
cell.set_style(style) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls", SaveFormat.EXCEL_97_TO_2003) |
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 is_text_wrapped del objeto Style.
from aspose.cells import Workbook | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Create Workbook Object | |
wb = Workbook() | |
# Open first Worksheet in the workbook | |
ws = wb.worksheets[0] | |
# Get Worksheet Cells Collection | |
cell = ws.cells | |
# Increase the width of First Column Width | |
cell.set_column_width(0, 35) | |
# Increase the height of first row | |
cell.set_row_height(0, 36) | |
# Add Text to the Firts Cell | |
cell.get(0, 0).put_value("I am using the latest version of Aspose.Cells to test this functionality") | |
# Make Cell's Text wrap | |
style = cell.get(0, 0).get_style() | |
style.is_text_wrapped = True | |
cell.get(0, 0).set_style(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 is_text_wrapped del objeto Style como true.
from aspose.cells import SaveFormat, Workbook | |
from os import os, path | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Create directory if it is not already present. | |
IsExists = path.isdir(dataDir) | |
if notIsExists: | |
os.makedirs(dataDir) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the worksheet | |
worksheet = workbook.worksheets[0] | |
# Accessing the "A1" cell from the worksheet | |
cell = worksheet.cells.get("A1") | |
# Adding some value to the "A1" cell | |
cell.put_value("Visit Aspose!") | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style = cell.get_style() | |
# Shrinking the text to fit according to the dimensions of the cell | |
style.shrink_to_fit = True | |
cell.set_style(style) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls", SaveFormat.EXCEL_97_TO_2003) |
Combinar celdas
Al igual que Microsoft Excel, Aspose.Cells para Python via .NET soporta fusionar varias celdas en una sola. Aspose.Cells para Python via .NET ofrece 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 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.
from aspose.cells import BackgroundType, Workbook | |
from aspose.pydrawing import Color | |
from os import os, path | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Create directory if it is not already present. | |
IsExists = path.isdir(dataDir) | |
if notIsExists: | |
os.makedirs(dataDir) | |
# Create a Workbook. | |
wbk = Workbook() | |
# Create a Worksheet and get the first sheet. | |
worksheet = wbk.worksheets[0] | |
# Create a Cells object ot fetch all the 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.get(5, 2).put_value("This is my value") | |
# Create a Style object to fetch the Style of C6 Cell. | |
style = worksheet.cells.get(5, 2).get_style() | |
# Create a Font object | |
font = style.font | |
# Set the name. | |
font.name = "Times New Roman" | |
# Set the font size. | |
font.size = 18 | |
# Set the font color | |
font.color = Color.blue | |
# Bold the text | |
font.is_bold = True | |
# Make it italic | |
font.is_italic = True | |
# Set the backgrond color of C6 Cell to Red | |
style.foreground_color = Color.red | |
style.pattern = BackgroundType.SOLID | |
# Apply the Style to C6 Cell. | |
cells.get(5, 2).set_style(style) | |
# Save the Workbook. | |
wbk.save(dataDir + "mergingcells.out.xls") |
La otra forma es llamar primero al método create_range de la colección cells para crear un rango de celdas a fusionar. El método create_range 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 text_direction del objeto Style. Aspose.Cells para Python via .NET 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 consistente con el idioma del primer carácter ingresado |
LEFT_TO_RIGHT | Orden de lectura de izquierda a derecha |
RIGHT_TO_LEFT | Orden de lectura de derecha a izquierda |
from aspose.cells import TextDirectionType, Workbook | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of first worksheet | |
worksheet = workbook.worksheets[0] | |
# Accessing the "A1" cell from the worksheet | |
cell = worksheet.cells.get("A1") | |
# Adding some value to the "A1" cell | |
cell.put_value("I am using the latest version of Aspose.Cells to test this functionality.") | |
# Gets style in the "A1" cell | |
style = cell.get_style() | |
# Shrinking the text to fit according to the dimensions of the cell | |
style.text_direction = TextDirectionType.LEFT_TO_RIGHT | |
cell.set_style(style) | |
# Saving the Excel file | |
workbook.save("book1.xlsx") |