Formato de celdas
Introducción
Cómo dar formato a las celdas usando los métodos GetStyle y SetStyle
Aplica diferentes tipos de estilos de formato en las celdas para establecer colores de fondo o primer plano, bordes, fuentes, alineaciones horizontales y verticales, nivel de sangría, dirección del texto, ángulo de rotación y mucho más.
Cómo utilizar los métodos GetStyle y SetStyle
Si los desarrolladores necesitan aplicar diferentes estilos de formato a diferentes celdas, entonces es mejor obtener el Style de la celda usando el método Cell.get_style, especificar los atributos de estilo y luego aplicar el formato usando el método Cell.set_style. A continuación se muestra un ejemplo para demostrar este enfoque de aplicar varios formatos a una celda.
from aspose.cells import BorderType, CellBorderType, TextAlignmentType, 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) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the 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("Hello Aspose!") | |
# Get the style from A1 cell | |
style = cell.get_style() | |
# Setting the vertical alignment | |
style.vertical_alignment = TextAlignmentType.CENTER | |
# Setting the horizontal alignment | |
style.horizontal_alignment = TextAlignmentType.CENTER | |
# Setting the font color of the text | |
style.font.color = Color.green | |
# Setting to shrink according to the text contained in it | |
style.shrink_to_fit = True | |
# Setting the bottom border color to red | |
style.borders.get(BorderType.BOTTOM_BORDER).color = Color.red | |
# Setting the bottom border type to medium | |
style.borders.get(BorderType.BOTTOM_BORDER).line_style = CellBorderType.MEDIUM | |
# Applying the style to A1 cell | |
cell.set_style(style) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls") |
Cómo utilizar el objeto Style para dar formato a diferentes celdas
Si los desarrolladores necesitan aplicar el mismo estilo de formato a diferentes celdas, pueden usar el objeto Style. Siga los pasos a continuación para usar el objeto Style:
- Agregue un objeto Style llamando al método create_style de la clase Workbook
- Acceda al nuevo objeto Style
- Establezca las propiedades/atributos deseados del objeto Style para aplicar la configuración de formato deseada
- Asigne el objeto configurado Style a las celdas deseadas
Este enfoque puede mejorar significativamente la eficiencia de sus aplicaciones y también ahorrar memoria.
from aspose.cells import BorderType, CellBorderType, TextAlignmentType, 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) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Adding a new worksheet to the Excel object | |
i = workbook.worksheets.add() | |
# Obtaining the reference of the first 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("Hello Aspose!") | |
# Adding a new Style | |
style = workbook.create_style() | |
# Setting the vertical alignment of the text in the "A1" cell | |
style.vertical_alignment = TextAlignmentType.CENTER | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style.horizontal_alignment = TextAlignmentType.CENTER | |
# Setting the font color of the text in the "A1" cell | |
style.font.color = Color.green | |
# Shrinking the text to fit in the cell | |
style.shrink_to_fit = True | |
# Setting the bottom border color of the cell to red | |
style.borders.get(BorderType.BOTTOM_BORDER).color = Color.red | |
# Setting the bottom border type of the cell to medium | |
style.borders.get(BorderType.BOTTOM_BORDER).line_style = CellBorderType.MEDIUM | |
# Assigning the Style object to the "A1" cell | |
cell.set_style(style) | |
# Apply the same style to some other cells | |
worksheet.cells.get("B1").set_style(style) | |
worksheet.cells.get("C1").set_style(style) | |
worksheet.cells.get("D1").set_style(style) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls") |
Cómo utilizar los estilos predefinidos de Microsoft Excel 2007
Si necesitas aplicar estilos de formateo diferentes para Microsoft Excel 2007, aplica estilos usando la API de Aspose.Cells para Python via .NET. A continuación se muestra un ejemplo para demostrar este enfoque al aplicar un estilo predefinido en una celda.
from aspose.cells import 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) | |
# Instantiate a new Workbook. | |
workbook = Workbook() | |
# Create a style object . | |
style = workbook.create_style() | |
# Input a value to A1 cell. | |
workbook.worksheets[0].cells.get("A1").put_value("Test") | |
# Apply the style to the cell. | |
workbook.worksheets[0].cells.get("A1").set_style(style) | |
# Save the Excel 2007 file. | |
workbook.save(dataDir + "book1.out.xlsx") |
Cómo formatear caracteres seleccionados en una celda
La sección sobre la configuración de fuentes explica cómo formatear texto en las celdas, pero solo explica cómo formatear todo el contenido de la celda. ¿Qué sucede si desea formatear solo caracteres seleccionados?
Aspose.Cells para Python via .NET también soporta esta característica. Este tema explica cómo usar esta característica de manera efectiva.
Cómo formatear caracteres seleccionados
Aspose.Cells para Python via .NET proporciona una clase Workbook que representa un archivo de Microsoft Excel. La clase Workbook contiene la colección worksheets que permite acceder a cada hoja en un archivo de Excel. Una hoja se representa mediante 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.
La clase Cell proporciona el método characters que toma los siguientes parámetros para seleccionar un rango de caracteres dentro de una celda:
- Índice de inicio, el índice del carácter desde el que comienza la selección.
- Número de caracteres, el número de caracteres a seleccionar.
El método characters devuelve una instancia de la clase FontSetting que permite a los desarrolladores formatear los caracteres de la misma manera que lo harían con una celda como se muestra a continuación en el ejemplo de código. En el archivo de salida, en la celda A1, la palabra ‘Visit’ tendrá un formato con la fuente predeterminada, pero ‘Aspose!’ está en negrita y azul.
from aspose.cells import 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) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the first(default) worksheet by passing its sheet index | |
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 font of selected characters to bold | |
cell.characters(6, 7).font.is_bold = True | |
# Setting the font color of selected characters to blue | |
cell.characters(6, 7).font.color = Color.blue | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls") |
Cómo formatear filas y columnas
A veces, los desarrolladores necesitan aplicar el mismo formato en filas o columnas. Aplicar formato en celdas una por una a menudo lleva más tiempo y no es una buena solución. Para abordar este tema, Aspose.Cells para Python via .NET ofrece una forma sencilla y rápida, detallada en este artículo.
Formato de filas y columnas
Aspose.Cells para Python via .NET proporciona una clase, Workbook, que representa un archivo de Microsoft Excel. La clase Workbook contiene una colección worksheets que permite acceder a cada hoja en el archivo de Excel. Una hoja se representa mediante la clase Worksheet. La clase Worksheet proporciona una colección cells. La colección cells proporciona una colección rows.
Cómo dar formato a una fila
Cada elemento en la colección rows representa un objeto Row. El objeto Row ofrece el método apply_style utilizado para establecer el formato de la fila. Para aplicar el mismo formato a una fila, use el objeto Style. Los pasos a continuación muestran cómo usarlo.
- Agregue un objeto Style a la clase Workbook llamando a su método create_style.
- Establezca las propiedades del objeto Style para aplicar la configuración de formato.
- Active los atributos relevantes para el objeto StyleFlag.
- Asigne el objeto configurado Style a la clase Row.
from aspose.cells import BorderType, CellBorderType, StyleFlag, TextAlignmentType, 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) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the first (default) worksheet by passing its sheet index | |
worksheet = workbook.worksheets[0] | |
# Adding a new Style to the styles | |
style = workbook.create_style() | |
# Setting the vertical alignment of the text in the "A1" cell | |
style.vertical_alignment = TextAlignmentType.CENTER | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style.horizontal_alignment = TextAlignmentType.CENTER | |
# Setting the font color of the text in the "A1" cell | |
style.font.color = Color.green | |
# Shrinking the text to fit in the cell | |
style.shrink_to_fit = True | |
# Setting the bottom border color of the cell to red | |
style.borders.get(BorderType.BOTTOM_BORDER).color = Color.red | |
# Setting the bottom border type of the cell to medium | |
style.borders.get(BorderType.BOTTOM_BORDER).line_style = CellBorderType.MEDIUM | |
# Creating StyleFlag | |
styleFlag = StyleFlag() | |
styleFlag.horizontal_alignment = True | |
styleFlag.vertical_alignment = True | |
styleFlag.shrink_to_fit = True | |
styleFlag.borders = True | |
styleFlag.font_color = True | |
# Accessing a row from the Rows collection | |
row = worksheet.cells.rows[0] | |
# Assigning the Style object to the Style property of the row | |
row.apply_style(style, styleFlag) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls") |
Cómo dar formato a una columna
La colección cells también proporciona una colección columns. Cada elemento en la colección columns representa un objeto Column. Similar a un objeto Row, el objeto Column también ofrece el método apply_style para dar formato a una columna.
from aspose.cells import BorderType, CellBorderType, StyleFlag, TextAlignmentType, 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) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the first (default) worksheet by passing its sheet index | |
worksheet = workbook.worksheets[0] | |
# Adding a new Style to the styles | |
style = workbook.create_style() | |
# Setting the vertical alignment of the text in the "A1" cell | |
style.vertical_alignment = TextAlignmentType.CENTER | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style.horizontal_alignment = TextAlignmentType.CENTER | |
# Setting the font color of the text in the "A1" cell | |
style.font.color = Color.green | |
# Shrinking the text to fit in the cell | |
style.shrink_to_fit = True | |
# Setting the bottom border color of the cell to red | |
style.borders.get(BorderType.BOTTOM_BORDER).color = Color.red | |
# Setting the bottom border type of the cell to medium | |
style.borders.get(BorderType.BOTTOM_BORDER).line_style = CellBorderType.MEDIUM | |
# Creating StyleFlag | |
styleFlag = StyleFlag() | |
styleFlag.horizontal_alignment = True | |
styleFlag.vertical_alignment = True | |
styleFlag.shrink_to_fit = True | |
styleFlag.borders = True | |
styleFlag.font_color = True | |
# Accessing a column from the Columns collection | |
column = worksheet.cells.columns[0] | |
# Applying the style to the column | |
column.apply_style(style, styleFlag) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls") |
Temas avanzados
- Configuración de alineación
- Configuración de bordes
- Establecer formatos condicionales de archivos de Excel y ODS.
- Temas y colores de Excel
- Configuración de relleno
- Configuración de fuente
- Dar formato a celdas de hoja de cálculo en un libro de trabajo
- Implementar el sistema de fechas 1904
- Combinar y descombinar celdas
- Configuración de números
- Obtener y establecer estilo para celdas