Angular Uso de hojas de trabajo
The Infragistics Angular Excel Engine's worksheet is where your data is kept. You can input data by working with the Worksheet's rows and cells and setting their corresponding values. The worksheet allows you to filter, sort, and customize the formats of the cells, as shown below.
Angular Using Worksheets Example
El siguiente código muestra las importaciones necesarias para utilizar los fragmentos de código siguientes:
import { Workbook } from "igniteui-angular-excel";
import { Worksheet } from "igniteui-angular-excel";
import { WorkbookFormat } from "igniteui-angular-excel";
import { Color } from "igniteui-angular-core";
import { CustomFilterCondition } from "igniteui-angular-excel";
import { ExcelComparisonOperator } from "igniteui-angular-excel";
import { FormatConditionTextOperator } from "igniteui-angular-excel";
import { OrderedSortCondition } from "igniteui-angular-excel";
import { RelativeIndex } from "igniteui-angular-excel";
import { SortDirection } from "igniteui-angular-excel";
import { WorkbookColorInfo } from "igniteui-angular-excel";
Configuring the Gridlines
Las líneas de cuadrícula se utilizan para separar visualmente las celdas de la hoja de trabajo. Puede mostrar u ocultar las líneas de la cuadrícula y también cambiar su color.
You can show or hide the gridlines using the showGridlines property of the displayOptions of the worksheet. The following code demonstrates how you can hide the gridlines in your worksheet:
var workbook = new Workbook(WorkbookFormat.Excel2007);
var worksheet = workbook.worksheets().add("Sheet1");
worksheet.displayOptions.showGridlines = false;
You can configure the gridlines' color using the gridlineColor property of the displayOptions of the worksheet. The following code demonstrates how you can change the gridlines in your worksheet to be red:
var workbook = new Workbook(WorkbookFormat.Excel2007);
var worksheet = workbook.worksheets().add("Sheet1");
worksheet.displayOptions.gridlineColor = "Red";
Configuring the Headers
Los encabezados de columnas y filas se utilizan para identificar visualmente columnas y filas. También se utilizan para resaltar visualmente la celda o región de celda actualmente seleccionada.
You can show or hide the column and row headers using the showRowAndColumnHeaders property of the displayOptions of the worksheet. The following code demonstrates how you can hide the row and column headers:
var workbook = new Workbook(WorkbookFormat.Excel2007);
var worksheet = workbook.worksheets().add("Sheet1");
worksheet.displayOptions.showRowAndColumnHeaders = false;
Configuring Editing of the Worksheet
By default, the worksheet objects that you save will be editable. You can disable editing of a worksheet by protecting it using the worksheet object's protect method. This method has a lot of nullable bool arguments that determine which pieces are protected, and one of these options is to allow editing of objects, which if set to false will prevent editing of the worksheet.
El siguiente código demuestra cómo deshabilitar la edición en su hoja de trabajo:
var workbook = new Workbook(WorkbookFormat.Excel2007);
var worksheet = workbook.worksheets().add("Sheet1");
worksheet.protect();
You can also use the worksheet object's protect method to protect a worksheet against structural changes.
When protection is set, you can set the cellFormat object's locked property on individual cells, rows, merged cell regions, or columns to override the worksheet object's protection on those objects. For example, if you need all cells of a worksheet to be read-only except for the cells of one column, you can protect the worksheet and then set the cellFormat object's locked property to false on a specific WorksheetColumn object. This will allow your users to edit cells within the column while disabling editing of the other cells in the worksheet.
El siguiente código demuestra cómo puede hacer esto:
var workbook = new Workbook(WorkbookFormat.Excel2007);
var worksheet = workbook.worksheets().add("Sheet1");
worksheet.protect();
worksheet.columns(0).cellFormat.locked = false;
Filtering Worksheet Regions
Filtering is done by setting a filter condition on a worksheet's WorksheetFilterSettings which can be retrieved from the worksheet object's filterSettings property. Filter conditions are only reapplied when they're added, removed, modified, or when the reapplyFilters method is called on the worksheet. They are not constantly evaluated as data within the region changes.
You can specify the region to apply the filter by using the setRegion method on the WorksheetFilterSettings object.
A continuación se muestra una lista de métodos y sus descripciones que puede utilizar para agregar un filtro a una hoja de trabajo:
| Método | Descripción |
|---|---|
applyAverageFilter |
Representa un filtro que puede filtrar datos en función de si están por debajo o por encima del promedio de todo el rango de datos. |
applyDatePeriodFilter |
Representa un filtro que puede filtrar fechas en un mes o trimestre de cualquier año. |
applyFillFilter |
Representa un filtro que filtrará las celdas según sus rellenos de fondo. Este filtro especifica un único CellFill. Las celdas con este relleno serán visibles en el rango de datos. Todas las demás celdas estarán ocultas. |
ApplyFixedValuesFilter |
Representa un filtro que puede filtrar celdas en función de valores fijos específicos, que pueden mostrarse. |
applyFontColorFilter |
Representa un filtro que filtrará las celdas según sus colores de fuente. Este filtro especifica un solo color. Las celdas con esta fuente de color serán visibles en el rango de datos. Todas las demás celdas estarán ocultas. |
applyIconFilter |
Representa un filtro que puede filtrar celdas según su icono de formato condicional. |
applyRelativeDateRangeFilter |
Representa un filtro que puede filtrar celdas de fecha en función de fechas relativas al momento en que se aplicó el filtro. |
applyTopOrBottomFilter |
Representa un filtro que puede filtrar en celdas en la parte superior o inferior de los valores ordenados. |
applyYearToDateFilter |
Representa un filtro que puede filtrar en celdas de fecha si las fechas ocurren entre el inicio del año actual y el momento en que se evalúa el filtro. |
applyCustomFilter |
Representa un filtro que puede filtrar datos según una o dos condiciones personalizadas. Estas dos condiciones de filtro se pueden combinar con una operación lógica "y" o "o". |
Puede utilizar el siguiente fragmento de código como ejemplo para agregar un filtro a una región de la hoja de trabajo:
var workbook = new Workbook(WorkbookFormat.Excel2007);
var worksheet = workbook.worksheets().add("Sheet1");
worksheet.filterSettings.setRegion("Sheet1!A1:A10");
worksheet.filterSettings.applyAverageFilter(0, AverageFilterType.AboveAverage);
Freezing and Splitting Panes
Puede congelar filas en la parte superior de su hoja de trabajo o columnas a la izquierda usando las funciones de paneles de congelación. Las filas y columnas congeladas permanecen visibles en todo momento mientras el usuario se desplaza. Las filas y columnas congeladas están separadas del resto de la hoja de trabajo por una única línea continua que no se puede eliminar.
In order to enable pane freezing, you need to set the panesAreFrozen property of the worksheet object's displayOptions to true. You can then specify the rows or columns to freeze by using the FrozenRows and FrozenColumns properties of the display options frozenPaneSettings, respectively.
You can also specify the first row in the bottom pane or first column in the right pane using the FirstRowInBottomPane and FirstColumnInRightPane properties, respectively.
El siguiente fragmento de código demuestra cómo utilizar las funciones de paneles congelados en una hoja de trabajo:
var workbook = new Workbook(WorkbookFormat.Excel2007);
var worksheet = workbook.worksheets().add("Sheet1");
worksheet.displayOptions.panesAreFrozen = true;
worksheet.displayOptions.frozenPaneSettings.frozenRows = 3;
worksheet.displayOptions.frozenPaneSettings.frozenColumns = 1;
worksheet.displayOptions.frozenPaneSettings.firstColumnInRightPane = 2;
worksheet.displayOptions.frozenPaneSettings.firstRowInBottomPane = 6;
Setting the Worksheet Zoom Level
You can change the zoom level for each worksheet independently using the MagnificationInNormalView property on the worksheet object's displayOptions. This property takes a value between 10 and 400 and represents the percentage of zoom that you wish to apply.
El siguiente código demuestra cómo puede hacer esto:
var workbook = new Workbook(WorkbookFormat.Excel2007);
var worksheet = workbook.worksheets().add("Sheet1");
worksheet.displayOptions.magnificationInNormalView = 300;
Worksheet Level Sorting
La clasificación se realiza estableciendo una condición de clasificación en un objeto a nivel de hoja de trabajo, ya sea en columnas o filas. Puede ordenar columnas o filas en orden ascendente o descendente.
This is done by specifying a region and sort type to the worksheet object's WorksheetSortSettings that can be retrieved using the sortSettings property of the sheet.
The sort conditions in a sheet are only reapplied when sort conditions are added, removed, modified, or when the reapplySortConditions method is called on the worksheet. Columns or rows will be sorted within the region. "Rows" is the default sort type.
El siguiente fragmento de código demuestra cómo aplicar una clasificación a una región de celdas en una hoja de trabajo:
var workbook = new Workbook(WorkbookFormat.Excel2007);
var worksheet = workbook.worksheets().add("Sheet1");
worksheet.sortSettings.sortConditions().addItem(new RelativeIndex(0), new OrderedSortCondition(SortDirection.Ascending));
Worksheet Protection
You can protect a worksheet by calling the protect method on the worksheet object. This method exposes many nullable bool parameters that allow you to restrict or allow the following user operations:
- Edición de celdas.
- Edición de objetos como formas, comentarios, gráficos u otros controles.
- Edición de escenarios.
- Filtrado de datos.
- Formateo de celdas.
- Insertar, eliminar y formatear columnas.
- Insertar, eliminar y formatear filas.
- Inserción de hipervínculos.
- Clasificación de datos.
- Uso de tablas dinámicas.
You can remove worksheet protection by calling the unprotect method on the worksheet object.
El siguiente fragmento de código muestra cómo habilitar la protección de todas las operaciones de usuario mencionadas anteriormente:
var workbook = new Workbook(WorkbookFormat.Excel2007);
var worksheet = workbook.worksheets().add("Sheet1");
worksheet.protect();
Worksheet Conditional Formatting
You can configure the conditional formatting of a worksheet object by using the many "Add" methods exposed on the conditionalFormats collection of that worksheet. The first parameter of these "Add" methods is the string region of the worksheet that you would like to apply the conditional format to.
Many of the conditional formats that you can add to your worksheet have a cellFormat property that determines the way that the WorksheetCell elements should look when the condition in that conditional format holds true. For example, you can use the properties attached to this cellFormat property such as fill and font to determine the background and font settings of your cells under a particular conditional format, respectively.
There are a few conditional formats that do not have a cellFormat property, as their visualization on the worksheet cell behaves differently. These conditional formats are the DataBarConditionalFormat, ColorScaleConditionalFormat, and IconSetConditionalFormat.
When loading a pre-existing workbook from Excel, the formats will be preserved when that workbook is loaded. The same is true for when you save the workbook out to an Excel file.
El siguiente ejemplo de código demuestra el uso de formatos condicionales en una hoja de trabajo:
var workbook = new Workbook(WorkbookFormat.Excel2007);
var worksheet = workbook.worksheets().add("Sheet1");
var color = new Color();
color.colorString = "Red";
var format = worksheet.conditionalFormats().addAverageCondition("A1:A10", FormatConditionAboveBelow.AboveAverage);
format.cellFormat.font.colorInfo = new WorkbookColorInfo(color);
API References
cellFormatColorScaleConditionalFormatconditionalFormatsDataBarConditionalFormatdisplayOptionsfilterSettingsshowGridlinesshowRowAndColumnHeaderssortSettingsworkbookWorksheetCellWorksheetColumnWorksheetFilterSettingsWorksheetSortSettingsworksheet