Angular usando planilhas
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
O código a seguir mostra as importações necessárias para usar os trechos de código abaixo:
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
As linhas de grade são usadas para separar visualmente as células na planilha. Você pode mostrar ou ocultar as linhas de grade e também alterar suas cores.
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
Os cabeçalhos de coluna e linha são usados para identificar visualmente colunas e linhas. Eles também são usados para destacar visualmente a célula ou região de célula selecionada no momento.
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.
O código a seguir demonstra como desabilitar a edição na sua planilha:
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.
O código a seguir demonstra como você pode fazer isso:
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.
Abaixo está uma lista de métodos e suas descrições que você pode usar para adicionar um filtro a uma planilha:
| Método | Descrição |
|---|---|
applyAverageFilter |
Representa um filtro que pode filtrar dados com base no fato de os dados estarem abaixo ou acima da média de todo o intervalo de dados. |
applyDatePeriodFilter |
Representa um filtro que pode filtrar datas em um mês ou trimestre de qualquer ano. |
applyFillFilter |
Representa um filtro que filtrará células com base em seus preenchimentos de fundo. Este filtro especifica um único CellFill. Células com este preenchimento ficarão visíveis no intervalo de dados. Todas as outras células ficarão ocultas. |
ApplyFixedValuesFilter |
Representa um filtro que pode filtrar células com base em valores específicos e fixos, que podem ser exibidos. |
applyFontColorFilter |
Representa um filtro que filtrará células com base em suas cores de fonte. Este filtro especifica uma única cor. Células com esta fonte de cor serão visíveis no intervalo de dados. Todas as outras células serão ocultadas. |
applyIconFilter |
Representa um filtro que pode filtrar células com base em seu ícone de formatação condicional. |
applyRelativeDateRangeFilter |
Representa um filtro que pode filtrar células de data com base em datas relativas a quando o filtro foi aplicado. |
applyTopOrBottomFilter |
Representa um filtro que pode filtrar células na parte superior ou inferior dos valores classificados. |
applyYearToDateFilter |
Representa um filtro que pode filtrar em células de data se as datas ocorrerem entre o início do ano atual e o momento em que o filtro é avaliado. |
applyCustomFilter |
Representa um filtro que pode filtrar dados com base em uma ou duas condições personalizadas. Essas duas condições de filtro podem ser combinadas com uma operação lógica "e" ou uma operação lógica "ou". |
Você pode usar o seguinte trecho de código como exemplo para adicionar um filtro a uma região da planilha:
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
Você pode congelar linhas na parte superior da sua planilha ou colunas à esquerda usando os recursos de painéis de congelamento. Linhas e colunas congeladas permanecem visíveis o tempo todo enquanto o usuário rola. As linhas e colunas congeladas são separadas do restante da planilha por uma única linha sólida, que não pode ser removida.
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.
Você também pode especificar a primeira linha no painel inferior ou a primeira coluna no painel direito usando asFirstRowInBottomPane propriedades e (eFirstColumnInRightPane também), respectivamente.
O trecho de código a seguir demonstra como usar os recursos de congelamento de painéis em uma planilha:
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.
O código a seguir demonstra como você pode fazer isso:
var workbook = new Workbook(WorkbookFormat.Excel2007);
var worksheet = workbook.worksheets().add("Sheet1");
worksheet.displayOptions.magnificationInNormalView = 300;
Worksheet Level Sorting
A classificação é feita definindo uma condição de classificação em um objeto de nível de planilha em colunas ou linhas. Você pode classificar colunas ou linhas em ordem crescente ou decrescente.
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.
O trecho de código a seguir demonstra como aplicar uma classificação a uma região de células em uma planilha:
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:
- Edição de células.
- Edição de objetos como formas, comentários, gráficos ou outros controles.
- Edição de cenários.
- Filtragem de dados.
- Formatação de células.
- Inserir, excluir e formatar colunas.
- Inserir, excluir e formatar linhas.
- Inserção de hiperlinks.
- Classificação de dados.
- Uso de tabelas dinâmicas.
You can remove worksheet protection by calling the unprotect method on the worksheet object.
O trecho de código a seguir mostra como habilitar a proteção de todas as operações de usuário listadas acima:
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.
O exemplo de código a seguir demonstra o uso de formatos condicionais em uma planilha:
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