Formato de celdas

Introducción

Formatee Cells usando los métodos GetStyle y SetStyle

Aplique diferentes tipos de estilos de formato en las celdas para establecer colores de fondo o de primer plano, bordes, fuentes, alineaciones horizontales y verticales, nivel de sangría, dirección del texto, ángulo de rotación y mucho más.

Uso de los métodos GetStyle y SetStyle

Si los desarrolladores necesitan aplicar diferentes estilos de formato a diferentes celdas, entonces es mejor obtener elEstilo de la celda utilizandoCell.GetStyle método, especifique los atributos de estilo y luego aplique el formato usandoCell.SetStylemétodo. A continuación se proporciona un ejemplo para demostrar este enfoque para aplicar varios formatos 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);
// 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");

Uso de objetos de estilo para formatear diferentes Cells

Si los desarrolladores necesitan aplicar el mismo estilo de formato a diferentes celdas, pueden usarEstilo objeto. Siga los pasos a continuación para usar elEstiloobjeto:

  1. Agrega unEstilo objeto llamando alCreateStyle metodo de laLibro de trabajoclase
  2. Accede a los recién agregadosEstiloobjeto
  3. Establezca las propiedades/atributos deseados delEstiloobjeto para aplicar la configuración de formato deseada
  4. Asignar el configuradoEstilooponerse a las celdas deseadas

Este enfoque puede mejorar en gran medida 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");

Usando Microsoft Excel 2007 Estilos predefinidos

Si necesita aplicar diferentes estilos de formato para Microsoft Excel 2007, aplique estilos usando Aspose.Cells API. A continuación se proporciona un ejemplo para demostrar este enfoque para 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");

Formateo de caracteres seleccionados en un Cell

Tratar con la configuración de fuente explica cómo dar formato al texto en las celdas, pero solo explica cómo dar formato a todo el contenido de la celda. ¿Qué sucede si desea formatear solo los caracteres seleccionados?

Aspose.Cells también admite esta función. Este tema explica cómo usamos esta característica de manera efectiva.

Dar formato a los caracteres seleccionados

Aspose.Cells proporciona una clase,Libro de trabajo que representa un archivo de Excel Microsoft. ÉlLibro de trabajo clase contiene elHojas de trabajo colección que permite el acceso a cada hoja de trabajo en un archivo de Excel. Una hoja de trabajo está representada por elHoja de cálculo clase. ÉlHoja de cálculo la clase proporciona unCells recopilación. Cada artículo en elCells colección representa un objeto de laCellclase.

ÉlCell la clase proporciona laCaracteresmétodo que toma los siguientes parámetros para seleccionar un rango de caracteres dentro de una celda:

  • Índice de comienzo, el índice del carácter desde el que comienza la selección.
  • Número de caracteres, el número de caracteres a seleccionar.

ÉlCaracteres método devuelve una instancia de laConfiguración de fuenteclass 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 ‘Visita’ se formateará con la fuente predeterminada pero ‘Aspose!’ es 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");

Formateo de filas y columnas

A veces, los desarrolladores necesitan aplicar el mismo formato en filas o columnas. Aplicar formato en las 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 que se analiza en detalle en este artículo.

Formateo de filas y columnas

Aspose.Cells proporciona una clase, elLibro de trabajo que representa un archivo de Excel Microsoft. ÉlLibro de trabajo la clase contiene unHojas de trabajo colección que permite el acceso a cada hoja de trabajo en el archivo de Excel. Una hoja de trabajo está representada por elHoja de cálculo clase. ÉlHoja de cálculo la clase proporciona unCells recopilación. ÉlCellscolección proporciona unaFilasrecopilación.

Dar formato a una fila

Cada artículo en elFilas colección representa unFila objeto. ÉlFilaobjeto ofrece laAplicarEstilo método utilizado para establecer el formato de la fila. Para aplicar el mismo formato a una fila, utilice elEstiloobjeto. Los pasos a continuación muestran cómo usarlo.

  1. Agrega unEstilo objetar a laLibro de trabajo clase llamando a suCreateStylemétodo.
  2. Selecciona elEstilopropiedades del objeto para aplicar la configuración de formato.
  3. Active los atributos relevantes para elBandera de estiloobjeto.
  4. Asignar el configuradoEstilo objetar a laFilaobjeto.
// 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");

Dar formato a una columna

ÉlCells colección también proporciona unacolumnas recopilación. Cada artículo en elcolumnas colección representa unColumna objeto. Similar a unFila objeto, elColumna objeto también ofrece laAplicarEstilométodo 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