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.GetStyle, especificar los atributos de estilo y luego aplicar el formato usando el método Cell.SetStyle. A continuación se muestra un ejemplo para demostrar este enfoque de aplicar varios formatos a una celda.

// 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 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("Hello Aspose!");
// Defining a Style object
Aspose.Cells.Style style;
// Get the style from A1 cell
style = cell.GetStyle();
// Setting the vertical alignment
style.VerticalAlignment = TextAlignmentType.Center;
// Setting the horizontal alignment
style.HorizontalAlignment = 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.ShrinkToFit = true;
// Setting the bottom border color to red
style.Borders[BorderType.BottomBorder].Color = Color.Red;
// Setting the bottom border type to medium
style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Medium;
// Applying the style to A1 cell
cell.SetStyle(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:

  1. Agregue un objeto Style llamando al método CreateStyle de la clase Workbook
  2. Acceda al nuevo objeto Style
  3. Establezca las propiedades/atributos deseados del objeto Style para aplicar la configuración de formato deseada
  4. Asigne el objeto configurado Style a las celdas deseadas

Este enfoque puede mejorar significativamente la eficiencia de sus aplicaciones y también ahorrar memoria.

// 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();
// Adding a new worksheet to the Excel object
int i = workbook.Worksheets.Add();
// Obtaining the reference of the first worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[i];
// Accessing the "A1" cell from the worksheet
Cell cell = worksheet.Cells["A1"];
// Adding some value to the "A1" cell
cell.PutValue("Hello Aspose!");
// Adding a new Style
Style style = workbook.CreateStyle();
// Setting the vertical alignment of the text in the "A1" cell
style.VerticalAlignment = TextAlignmentType.Center;
// Setting the horizontal alignment of the text in the "A1" cell
style.HorizontalAlignment = 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.ShrinkToFit = true;
// Setting the bottom border color of the cell to red
style.Borders[BorderType.BottomBorder].Color = Color.Red;
// Setting the bottom border type of the cell to medium
style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Medium;
// Assigning the Style object to the "A1" cell
cell.SetStyle(style);
// Apply the same style to some other cells
worksheet.Cells["B1"].SetStyle(style);
worksheet.Cells["C1"].SetStyle(style);
worksheet.Cells["D1"].SetStyle(style);
// Saving the Excel file
workbook.Save(dataDir + "book1.out.xls");

Cómo utilizar los estilos predefinidos de Microsoft Excel 2007

Si necesita aplicar diferentes estilos de formato para Microsoft Excel 2007, aplique estilos usando la API de Aspose.Cells. A continuación se muestra un ejemplo para demostrar este enfoque de aplicar un estilo predefinido en una celda.

// 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);
// Instantiate a new Workbook.
Workbook workbook = new Workbook();
// Create a style object .
Style style = workbook.CreateStyle();
// Input a value to A1 cell.
workbook.Worksheets[0].Cells["A1"].PutValue("Test");
// Apply the style to the cell.
workbook.Worksheets[0].Cells["A1"].SetStyle(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 también admite esta función. Este tema explica cómo usar esta función de manera efectiva.

Cómo formatear caracteres seleccionados

Aspose.Cells 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 de cálculo en un 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.

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.

// 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 first(default) worksheet by passing its sheet index
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("Visit Aspose!");
// Setting the font of selected characters to bold
cell.Characters(6, 7).Font.IsBold = 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 problema, Aspose.Cells proporciona una forma simple y rápida discutida en detalle en este artículo.

Formato de filas y columnas

Aspose.Cells proporciona una clase, el Workbook que representa un archivo de Microsoft Excel. La clase Workbook contiene una colección Worksheets que permite 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. 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 ApplyStyle 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.

  1. Agregue un objeto Style a la clase Workbook llamando a su método CreateStyle.
  2. Establezca las propiedades del objeto Style para aplicar la configuración de formato.
  3. Active los atributos relevantes para el objeto StyleFlag.
  4. Asigne el objeto configurado Style a la clase Row.
// 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 first (default) worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[0];
// Adding a new Style to the styles
Style style = workbook.CreateStyle();
// Setting the vertical alignment of the text in the "A1" cell
style.VerticalAlignment = TextAlignmentType.Center;
// Setting the horizontal alignment of the text in the "A1" cell
style.HorizontalAlignment = 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.ShrinkToFit = true;
// Setting the bottom border color of the cell to red
style.Borders[BorderType.BottomBorder].Color = Color.Red;
// Setting the bottom border type of the cell to medium
style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Medium;
// Creating StyleFlag
StyleFlag styleFlag = new StyleFlag();
styleFlag.HorizontalAlignment = true;
styleFlag.VerticalAlignment = true;
styleFlag.ShrinkToFit = true;
styleFlag.Borders = true;
styleFlag.FontColor = true;
// Accessing a row from the Rows collection
Row row = worksheet.Cells.Rows[0];
// Assigning the Style object to the Style property of the row
row.ApplyStyle(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 ApplyStyle para dar formato a una columna.

// 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 first (default) worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[0];
// Adding a new Style to the styles
Style style = workbook.CreateStyle();
// Setting the vertical alignment of the text in the "A1" cell
style.VerticalAlignment = TextAlignmentType.Center;
// Setting the horizontal alignment of the text in the "A1" cell
style.HorizontalAlignment = 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.ShrinkToFit = true;
// Setting the bottom border color of the cell to red
style.Borders[BorderType.BottomBorder].Color = Color.Red;
// Setting the bottom border type of the cell to medium
style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Medium;
// Creating StyleFlag
StyleFlag styleFlag = new StyleFlag();
styleFlag.HorizontalAlignment = true;
styleFlag.VerticalAlignment = true;
styleFlag.ShrinkToFit = true;
styleFlag.Borders = true;
styleFlag.FontColor = true;
// Accessing a column from the Columns collection
Column column = worksheet.Cells.Columns[0];
// Applying the style to the column
column.ApplyStyle(style, styleFlag);
// Saving the Excel file
workbook.Save(dataDir + "book1.out.xls");

Temas avanzados