React Usando células

    The WorksheetCell objects in an Excel worksheet is the object that holds your actual data values for the worksheet. This topic goes over the many operations that you can perform on these cells, such as accessing them and their regions by name, adding formulas and comments to the cells, and merging and formatting them.

    React Using Cells Example

    References

    O código a seguir mostra as importações necessárias para usar os trechos de código abaixo:

    import { Workbook } from "igniteui-react-excel";
    import { WorkbookFormat } from "igniteui-react-excel";
    import { Worksheet } from "igniteui-react-excel";
    import { WorksheetTable } from "igniteui-react-excel";
    import { NamedReference } from "igniteui-react-excel";
    import { WorksheetCellComment } from "igniteui-react-excel";
    import { FormattedString } from "igniteui-react-excel";
    

    Referencing Cells and Regions

    You can access a WorksheetCell object or a WorksheetRegion object by calling the worksheet object’s getCell or getRegion methods, respectively. Both methods accept a string parameter that references a cell. Getting a reference to a cell is useful when applying formats or working with formulas and cell contents.

    O código de exemplo a seguir demonstra como fazer referência a células e regiões:

    var workbook = new Workbook();
    var worksheet = workbook.worksheets().add("Sheet1");
    
    //Accessing a single cell
    var cell = worksheet.getCell("E2");
    //Accessing a range of cells
    var region = worksheet.getRegion("G1:G10");
    

    Accessing Cells and Regions by Name

    No Microsoft Excel, células individuais, bem como regiões de células, podem ter nomes atribuídos a elas. O nome de uma célula ou região pode ser usado para fazer referência a essa célula ou região em vez de seu endereço.

    The Infragistics React Excel Library supports the referencing of cells and regions by name through the getCell and getRegion methods of the worksheet object. You refer to the cell or region using the NamedReference instance that refers to that cell or region.

    Você pode usar o seguinte trecho de código como exemplo para nomear uma célula ou região:

    var workbook = new Workbook();
    var worksheet = workbook.worksheets().add("Sheet1");
    
    var cell_reference = workbook.namedReferences().add("myCell", "=Sheet1:A1");
    var region_reference = workbook.namedReferences().add("myRegion", "=Sheet1!A1:B2");
    

    O código a seguir pode ser usado para obter a célula e a região referenciadas pelas referências nomeadas "myCell" e "myRegion" acima:

    var cell = worksheet.getCell("myCell");
    var region = worksheet.getRegion("myRegion");
    

    Adding a Comment to a Cell

    A comment allows you to display hints or notes for a cell when the end user’s mouse hovers over a cell. The comments display as a tooltip-like callout that contains text. The Infragistics React Excel Library allows you to add comments to a cell by setting a WorksheetCell object’s comment property.

    O código de exemplo a seguir demonstra como adicionar um comentário a uma célula:

    var workbook = new Workbook();
    var worksheet = workbook.worksheets().add("Sheet1");
    
    var cellComment = new WorksheetCellComment();
    var commentText = new FormattedString("This cell has a comment.");
    cellComment.text = commentText;
    
    worksheet.rows(0).cells(0).comment = cellComment;
    

    Adding a Formula to a Cell

    The Infragistics React Excel Library allows you to add Microsoft Excel formulas to a cell or group of cells in a worksheet. You can do this using the WorksheetCell object’s applyFormula method or by instantiating a formula object and applying it to a cell. Regardless of the manner in which you apply a formula to a cell, you can access the formula object using the WorksheetCell object’s formula property. If you need the value, use the cell’s value property.

    O código a seguir mostra como adicionar uma fórmula a uma célula.

     var workbook = new Workbook();
     var worksheet = workbook.worksheets().add("Sheet1");
     worksheet.rows(5).cells(0).applyFormula("=SUM(A1:A5)");
    
     //Using a Formula object to apply a formula
     var sumFormula = Formula.parse("=SUM(A1:A5)", CellReferenceMode.A1);
     sumFormula.applyTo(worksheet.rows(5).cells(0));
    

    Copying a Cell’s Format

    Cells can have different formatting, including background color, format string, and font style. If you need a cell to have the same format as a previously formatted cell, instead of individually setting each option exposed by the WorksheetCell object’s cellFormat property, you can call the cellFormat object’s setFormatting method and pass it a cellFormat object to copy. This will copy every format setting from the first cell to the second cell. You can also do this for a row, merged cell region, or column.

    O código a seguir mostra como copiar o formato da 2ª coluna para a 4ª coluna:

    var workbook = new Workbook();
    var worksheet = workbook.worksheets().add("Sheet1");
    
    //Format 2nd column
    worksheet.columns(1).cellFormat.fill = CellFill.createSolidFill("Blue");
    worksheet.columns(1).cellFormat.font.bold = true;
    
    //Copy format of 2nd column to 4th column
    worksheet.columns(3).cellFormat.setFormatting(worksheet.columns(1).cellFormat);
    

    Formatting a Cell

    The Infragistics React Excel Library allows you to customize the look and behavior of a cell. You can customize a cell by setting properties exposed by the cellFormat property of the WorksheetCell, WorksheetRow, WorksheetColumn, or WorksheetMergedCellsRegion objects.

    Você pode personalizar todos os aspectos da aparência de uma célula. Você pode definir a fonte, o plano de fundo e as bordas de uma célula, bem como o alinhamento e a rotação do texto. Você pode até aplicar um formato diferente caractere por caractere para o texto de uma célula.

    Você também pode formatar valores de célula atribuindo uma cadeia de caracteres de formato. Uma cadeia de caracteres de formato aceitável segue os padrões de formato e códigos de formatação tradicionais.

    O código a seguir mostra como formatar uma célula para exibir números como moeda:

    var workbook = new Workbook(format);
    var workbook = workbook.worksheets().add("Sheet1");
    
    worksheet.columns(2).cellFormat.formatString = "\"$\"#,##0.00";
    

    Excel 2007 Color Model

    A paleta de cores é análoga à caixa de diálogo de cores na interface do usuário do Microsoft Excel 2007. Você pode abrir essa caixa de diálogo de cores navegando até Opções do Excel => Salvar => Cores.

    You can create all possible fill types using static properties and methods on the CellFill class. They are as follows:

    • NoColor - A property that represents a fill with no color, which allows a background image of the worksheet, if any, to show through.

    • CreateSolidFill - Returns a CellFillPattern instance which has a pattern style of Solid and a background color set to the color or WorkbookColorInfo specified in the method.

    • CreatePatternFill - Returns a CellFillPattern instance which has the specified pattern style and the color or WorkbookColorInfo values, specified for the background and pattern colors.

    • CreateLinearGradientFill - Returns a CellFillLinearGradient instance with the specified angle and gradient stops.

    • CreateRectangularGradientFill - Returns a CellFillRectangularGradient instance with the specified left, top, right, and bottom of the inner rectangle and gradient stops. If the inner rectangle values are not specified, the center of the cell is used as the inner rectangle.

    Os tipos derivados, representando os vários preenchimentos que podem ser criados, são os seguintes:

    • CellFillPattern - A pattern that represents a cell fill of no color, a solid color, or a pattern fill for a cell. It has background color info and a pattern color info which correspond directly to the color sections in the Fill tab of the Format Cells dialog of Excel.

    • CellFillLinearGradient - Represents a linear gradient fill. It has an angle, which is degrees clockwise of the left to right linear gradient, and a gradients stops collection which describes two or more color transitions along the length of the gradient.

    • CellFillRectangularGradient - Represents a rectangular gradient fill. It has top, left, right, and bottom values, which describe, in relative coordinates, the inner rectangle from which the gradient starts and goes out to the cell edges. It also has a gradient stops collection which describes two or more color transitions along the path from the inner rectangle to the cell edges.

    The following code snippet demonstrates how to create a solid fill in a WorksheetCell:

    var workbook = new Workbook();
    var worksheet = workbook.worksheets().add("Sheet1");
    
    var cellFill = CellFill.createSolidFill("Blue");
    worksheet.rows(0).cells(0).cellFormat.fill = cellFill;
    

    Você pode especificar uma cor (a cor do plano de fundo das células do Excel, borda, etc.) usando gradientes lineares e retangulares nas células. Quando as pastas de trabalho com esses gradientes são salvas em .xls formato de arquivo e abertas no Microsoft Excel 2007/2010, os gradientes ficam visíveis, mas quando esses arquivos são abertos no Microsoft Excel 2003, a célula é preenchida com a cor sólida da primeira parada de gradiente.

    Estas são as maneiras pelas quais uma cor pode ser definida, da seguinte maneira:

    • A cor automática (que é a cor do sistema WindowText)

    • Qualquer cor RGB definida pelo usuário

    • A theme color

    Se uma cor RGB ou de tema for usada, uma tonalidade opcional poderá ser aplicada para clarear ou escurecer a cor. Essa tonalidade não pode ser definida diretamente na interface do usuário do Microsoft Excel 2007, mas várias cores na paleta de cores exibidas para o usuário são, na verdade, cores de tema com tonalidades aplicadas.

    Cada pasta de trabalho tem 12 cores de tema associadas. Eles são os seguintes:

    • Light 1

    • Light 2

    • Dark 1

    • Dark 2

    • Accent1

    • Accent2

    • Accent3

    • Accent4

    • Accent5

    • Accent6

    • Hiperlink

    • Followed Hyperlink

    • Há valores padrão quando uma pasta de trabalho é criada, que podem ser personalizados por meio do Excel.

    Colors are defined by the WorkbookColorInfo class, which is a sealed immutable class. The class has a static Automatic property, which returns the automatic color, and there are various constructors which allow you to create a WorkbookColorInfo instance with a color or a theme value and an optional tint.

    The getResolvedColor method on WorkbookColorInfo allows you to determine what color will actually be seen by the user when they open the file in Excel.

    If the WorkbookColorInfo represents a theme color, you must pass in a Workbook instance to the method so it can get the theme color’s RGB value from the workbook.

    Ao salvar nos formatos de arquivo mais recentes, como .xlsx, as informações de cores mais recentes são salvas diretamente no arquivo. Ao salvar em um formato de arquivo mais antigo, como .xls, o índice para a cor mais próxima na paleta será salvo. Além disso, os formatos mais antigos têm registros de recursos futuros que podem ser salvos para indicar as informações de cores mais recentes.

    Quando os formatos mais antigos são abertos no Microsoft Excel 2003 e versões anteriores, esses registros de recursos futuros são ignorados, mas quando os formatos de arquivo mais antigos são abertos no Excel 2007 e posterior, seus registros são lidos e as informações de cor deles substituem a cor indexada que foi carregada anteriormente a partir dos registros de formato normal.

    Excel Format Support

    You can set a host of different formats on a WorksheetCell by using the cellFormat object returned by the cellFormat property of that cell. This cellFormat object enables you to style many different aspects of the cell such as borders, font, fill, alignments, and whether or not the cell should shrink to fit or be locked.

    You can also access the built-in styles to Microsoft Excel 2007 using the styles collection of the workbook object. The full list of styles in Excel can be found in the Cell Styles gallery of the Home tab of Microsoft Excel 2007.

    There is a special type of style on the workbook's styles collection known as the "normal" style, which can be accessed using that collection's normalStyle property, or by indexing into the collection with the name "Normal".

    The normalStyle contains the default properties for all cells in the workbook, unless otherwise specified on a row, column, or cell. Changing the properties on the normalStyle will change all of the default cell format properties on the workbook. This is useful, for example, if you want to change the default font for your workbook.

    You can clear the styles collection or reset it to its predefined state by using the clear and reset methods, respectively. Both of these will remove all user-defined styles, but clear will clear the styles collection entirely.

    With this feature, a style property has been added to the cellFormat object. This is a reference to a WorkbookStyle instance, representing the parent style of the format. For formats of a style, this property will always be null, because styles cannot have a parent style. For row, column, and cell formats, the style property always returns the normalStyle by default.

    If the style property is set to null, it will revert back to the normalStyle. If it is set to another style in the styles collection, that style will now hold the defaults for all unset properties on the cell format.

    When the style property is set on a cell format, the format options included on the style are removed from the cell format. All other properties are left intact. For example, if a cell style including border formatting was created and that style was set as the cell's style, the border format option on the cell format would be removed and the cell format only includes fill formatting.

    Quando um sinalizador de opção de formato é removido de um formato, todas as propriedades associadas são redefinidas para seus valores não definidos, de modo que as propriedades de borda do formato de célula são implicitamente redefinidas para valores padrão/não definidos.

    You can determine what would really be seen in cells by using the getResolvedCellFormat method on classes which represent a row, column, cell, and merged cell.

    This method returns a cellFormat instance which refers back to the associated cellFormat on which it is based. So subsequent changes to the cellFormat property will be reflected in the instance returned from a getResolvedCellFormat call.

    Merging Cells

    Além de definir o valor ou o formato das células, você também pode mesclar células para fazer com que duas ou mais células apareçam como uma. Se você mesclar células, elas deverão estar em uma região retangular.

    When you merge cells, each cell in the region will have the same value and cell format. The merged cells will also be associated with the same WorksheetMergedCellsRegion object, accessible from their associatedMergedCellsRegion property. The resultant WorksheetMergedCellsRegion object will also have the same value and cell format as the cells.

    Definir o valor (ou formato da célula) da região ou de qualquer célula da região alterará o valor de todas as células e da região. Se você desfazer a mesclagem de células, todas as células mescladas anteriormente manterão o formato de célula compartilhada que tinham antes de serem desmescladas. No entanto, somente a célula superior esquerda da região manterá o valor compartilhado.

    In order to create a merged cell region, you must add a range of cells to the worksheet object’s mergedCellsRegions collection. This collection exposes an Add method that takes four integer parameters. The four parameters determine the index of the starting row and column (top-left most cell) and the index of the ending row and column (bottom-right most cell).

    var workbook = new Workbook();
    var worksheet = workbook.worksheets().add("Sheet1");
    
    // Make some column headers
    worksheet.rows(1).cells(1).value = "Morning";
    worksheet.rows(1).cells(2).value = "Afternoon";
    worksheet.rows(1).cells(3).value = "Evening";
    
    // Create a merged region from column 1 to column 3
    var mergedRegion1 =  ws.mergedCellsRegions().add(0, 1, 0, 3);
    
    // Set the value of the merged region
    mergedRegion1.value = "Day 1";
    
    // Set the cell alignment of the middle cell in the merged region.
    // Since a cell and its merged region shared a cell format, this will ultimately set the format of the merged region
    worksheet.rows(0).cells(2).cellFormat.alignment = HorizontalCellAlignment.Center;
    

    Retrieving the Cell Text as Displayed in Excel

    O texto exibido em uma célula depende de vários fatores além do valor real da célula, como a cadeia de caracteres de formato e a largura da coluna em que a célula está contida.

    A cadeia de caracteres de formato determina como o valor da célula é convertido em texto e qual caractere literal deve ser exibido com o valor formatado. Você pode encontrar informações mais detalhadas sobre códigos de formato aqui.

    A quantidade de espaço horizontal disponível em uma célula desempenha um papel importante na forma como o valor é exibido para o usuário.

    O texto exibido pode ser diferente dependendo da largura variável da coluna.

    Ao exibir números e usar a string de formato contendo "Geral" ou"@", existem vários formatos que são tentados para encontrar uma formatação que se ajuste à largura da célula. Uma lista de formatos de exemplo é mostrada abaixo:

    • Valor Normal- O número é exibido como seria se houvesse uma quantidade ilimitada de espaço.

    • Remover dígitos decimais- Os dígitos decimais serão removidos um de cada vez até que seja encontrado um formato adequado. Por exemplo, um valor de 12345.6789 será reduzido para os seguintes formatos até que um se encaixe: 12345.679, 12345.68, 12345.7 e 12346. Isso será interrompido quando o primeiro dígito significativo for o único restante, portanto, por exemplo, valores como 0,0001234567890 só podem ser reduzidos para 0,0001.

    • Científico, 5 dígitos decimais- O número é exibido na forma de 0,00000E+00, como 1,23457E+09 ou 1,23457E-04

    • Científico, 4 dígitos decimais- O número é exibido na forma de 0,0000E+00, como 1,2346E+09 ou 1,23456E-04

    • Científico, 3 dígitos decimais- O número é exibido na forma de 0.000E+00, como 1.235E+09 ou 1.235E-0

    • Científico, 2 dígitos decimais- O número é exibido na forma de 0,00E + 00, como 1,23E + 09 ou 1,23E-04

    • Científico, 1 dígitos decimais- O número é exibido na forma de 0.0E + 00, como 1.2E + 09 ou 1.2E-04

    • Científico, 0 dígitos decimais- O número é exibido na forma de 0E+00, como 1E+09 ou 1E-04

    • Valor arredondado- Se o primeiro dígito significativo estiver na parte decimal do número, o valor será arredondado para o valor inteiro mais próximo. Por exemplo, para um valor 0,0001234567890, ele será arredondado para 0 e o texto exibido na célula será 0.

    • Marcas de hash- Se nenhuma versão condensada do número puder ser exibida, os hashes (#) serão repetidos na largura da célula.

    • Cadeia de caracteres vazia- Se nenhuma marca de hash couber na célula, uma cadeia de caracteres vazia será retornada como texto da célula exibida.

    Se a cadeia de caracteres de formato para o valor numérico não contiver Geral ou @, haverá apenas os seguintes estágios de redimensionamento: Valor normal, Marcas de hash, Cadeia de caracteres vazia

    Se um texto for usado na célula, o texto exibido na célula sempre terá o valor total, independentemente de estar cortado ou não na célula.

    O único momento em que esse não é o caso é quando os caracteres de preenchimento são usados na string de formato. Em seguida, o valor será exibido como todas as marcas de hash quando não houver espaço suficiente para o texto.

    You can set the worksheet's displayOptions' showFormulasInCells property to have formulas be displayed in cells instead of their results, and format strings and cell widths are ignored. Text values display as if their format string were @ , non-integral numeric values display as if their format string were 0.0 and integral numeric values display as if their format string were 0 .

    Além disso, se o valor não couber, ele não será exibido como todos os hashes. O texto de exibição ainda retornará seu texto completo como o texto da célula, mesmo que não seja totalmente visto.

    The following code snippet demonstrates the usage of the getText method to get the text as it would be displayed in Excel:

    var workbook = new Workbook();
    var worksheet = this.workbook.worksheets().add("Sheet1");
    
    var cellText = worksheet.rows(0).cells(0).getText();
    

    API References