Uso de Estilos y SheetViews en Workbooks para .NET

Ahora que hemos cubierto los conceptos básicos de la creación de un documento xlsx, y aprendido a añadir y modificar el contenido de una hoja de cálculo incluyendo celdas y tablas, vamos a ver cómo hacer que se vea bien, aprovechando los estilos y SheetViews.

Más información Cuadernos Xeed para .NET

Ahora que hemos cubierto los conceptos básicos de la creación de un documento xlsx, y aprendido a añadir y modificar el contenido de un Hoja de trabajo incluyendo Células y TablasVamos a ver cómo hacer que se vea bien aprovechando los Estilos y las SheetViews.

Note:

  • At the time of this writing, more options have been added to the Style and SheetView classes and will be included in a future release of Xceed Workbooks for .NET.
    We will cover these new options in a part 2 article once they are available.

¿Qué es un estilo?

En pocas palabras, un Estilo es un grupo de ajustes para cambiar el aspecto de las celdas, que pueden aplicarse a una celda específica. Celdalas células de un Columnao las células de un Fila.

En concreto, estos ajustes incluyen actualmente:

  • Font: the Font to use for the current Style.
  • Alignment: the horizontal and vertical alignments used to align the content of a cell.
  • CustomFormat: the format used to display the content of a Cell (null by default, setting this property will overwrite the PredefinedNumberFormatId property)
  • PredefinedNumberFormatId: the predefined number format with an Id (0 by default, setting this property will overwrite the CustomFormat property)

Aprovechar los Estilos es una gran manera de tener un formato consistente en sus Libros de Trabajo y Hojas de Cálculo.

Aplicar un estilo

Se puede especificar un Estilo en un Celdacélulas de un Columnao células de un Fila.

Sin embargo, esto nos lleva a la siguiente pregunta: ¿qué pasa si tenemos una Celda afectada por más de un Estilo? Por ejemplo, tenemos un Estilo en la Columna B y también un Estilo en la 5ta Fila, en esta situación ¿qué Estilo se usaría para la Celda en "B5"? La prioridad se determina en el siguiente orden: Celda, Fila, Columna. Esto significa que en nuestro ejemplo, si no hay un Estilo aplicado directamente a la Celda en "B5", se usaría el de la Fila.

En los ejemplos siguientes se parte de la siguiente disposición inicial del código:

using( var document = Workbook.Load( "testDoc.xlsx" ));
{
	var worksheet = document.Worksheets[ 0 ];
		
	// Styling a specific Cell using its address
	worksheet.Cells[ "B2" ].Style. [...]

	// Styling a specific Cell using its row and column index
	worksheet.Cells[ 1, 1 ].Style. [...]

	// Styling the Cells of a Column
	worksheet.Columns[ 2 ].Style. [...]

	// Styling the Cells of a Row
	worksheet.Rows[ 3 ].Style. [...]

	document.Save();
}

Fuente (propiedades disponibles) aquí)

// Specific Cell
worksheet.Cells[ "B1" ].Style.Font = new Font() { Bold = true, Size = 15.5d };

// Column
worksheet.Columns[ 2 ].Style.Font = new Font() { Name = "Lucida Fax", Italic = true, Underline = true, UnderlineType = UnderlineType.Double };

// Row
worksheet.Rows[ 3 ].Style.Font = new Font() { Strikethrough = true, Size = 18d };

Alineación (valores disponibles para HorizontalAlignment y AlineaciónVertical)

// Specific Cell
worksheet.Cells[ "B1" ].Style.Alignment.Horizontal = HorizontalAlignment.Center;
worksheet.Cells[ "B1" ].Style.Alignment.Vertical = VerticalAlignment.Center;

// Column
worksheet.Columns[ 2 ].Style.Alignment = new Alignment( HorizontalAlignment.Justify, VerticalAlignment.Center);

// Row
worksheet.Rows[ 3 ].Style.Alignment.Horizontal = HorizontalAlignment.CenterAcrossSelection;

Formato personalizado

// Cell B2 contains 25.6 displayed as "$25.6000"
worksheet.Cells[ 1, 1 ].Value = 25.6;
worksheet.Cells[ 1, 1 ].Style.CustomFormat = "$0.0000";

// Cell C3 contains a date formatted to display as "10:22 AM"
worksheet.Cells[ 2, 2 ].Value = new DateTime( 2021, 7, 1, 10, 22, 33 );
worksheet.Cells[ 2, 2 ].Style.CustomFormat = "h:mm AM/PM";

// Column
worksheet.Columns[ 2 ].Style.CustomFormat = "h:mm AM/PM";

// Row
worksheet.Rows[ 3 ].Style.CustomFormat = "$0.0000";

PredefinedNumberFormatId (valores disponibles aquí)

// Cell D4 contains 33.5 set to format "0.00" to display the value as "33.50"
worksheet.Cells[ "D4" ].Value = 33.5;
worksheet.Cells[ "D4" ].Style.PredefinedNumberFormatId = 2;

// Column with dates formatted as mm-dd-yy
worksheet.Columns[ 2 ].Style.PredefinedNumberFormatId = 14;

// Row with time formatted as [h]:mm:ss
worksheet.Rows[ 3 ].Style.PredefinedNumberFormatId = 46;

¿Qué es una SheetView?

Una SheetView es una forma de permitir la creación de vistas personalizadas en un Hoja de trabajo.

La clase SheetView representa una vista de hoja única de un Hoja de trabajo.

Note:

  • At the time of writing, only one SheetView per Worksheet is supported.

Uso de una SheetView

La clase SheetView actualmente soporta las siguientes propiedades:

  • ActiveCellAddress: the active Cell in the Worksheet, which is the one with focus.
  • TopLeftCellAddress: the Cell to be displayed as the top left position in the Worksheet view.
// Setting a SheetView
	using( var document = Workbook.Load( "testDoc.xlsx" ));
	{
		var worksheet = doc.Worksheets[ 0 ];        
		worksheet.SheetView.ActiveCellAddress = "C2";
		worksheet.SheetView.TopLeftCellAddress = "B1";
		document.Save();
	}

Para más información, consulte el documentación.