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
El siguiente código muestra las importaciones necesarias para utilizar los fragmentos de código siguientes:
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.
El siguiente código de ejemplo demuestra cómo hacer referencia a celdas y regiones:
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
En Microsoft Excel, las celdas individuales, así como las regiones de celdas, pueden tener nombres asignados. El nombre de una celda o región se puede utilizar para hacer referencia a esa celda o región en lugar de su dirección.
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.
Puede utilizar el siguiente fragmento de código como ejemplo para nombrar una celda o región:
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");
El siguiente código se puede utilizar para obtener la celda y la región a las que hacen referencia las referencias denominadas "myCell" y "myRegión" anteriores:
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.
El siguiente código de ejemplo demuestra cómo agregar un comentario a una celda:
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.
El siguiente código le muestra cómo agregar una fórmula a una celda.
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.
El siguiente código le muestra cómo copiar el formato de la segunda columna a la cuarta columna:
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.
Puede personalizar todos los aspectos de la apariencia de una celda. Puede configurar la fuente, el fondo y los bordes de una celda, así como la alineación y rotación del texto. Incluso puedes aplicar un formato diferente carácter por carácter para el texto de una celda.
También puede formatear los valores de las celdas asignando una cadena de formato. Una cadena de formato aceptable sigue los estándares y códigos de formato tradicionales.
El siguiente código le muestra cómo formatear una celda para mostrar números como moneda:
var workbook = new Workbook(format);
var workbook = workbook.worksheets().add("Sheet1");
worksheet.columns(2).cellFormat.formatString = "\"$\"#,##0.00";
Excel 2007 Color Model
La paleta de colores es análoga al diálogo de colores en la interfaz de usuario de Microsoft Excel 2007. Puede abrir este cuadro de diálogo de color navegando a Opciones de Excel => Guardar => Colores.
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 aCellFillPatterninstance which has a pattern style ofSolidand a background color set to thecolororWorkbookColorInfospecified in the method.CreatePatternFill- Returns aCellFillPatterninstance which has the specified pattern style and thecolororWorkbookColorInfovalues, specified for the background and pattern colors.CreateLinearGradientFill- Returns aCellFillLinearGradientinstance with the specified angle and gradient stops.CreateRectangularGradientFill- Returns aCellFillRectangularGradientinstance 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.
Los tipos derivados, que representan los distintos rellenos que se pueden crear, son los siguientes:
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;
Puede especificar un color (el color del fondo, borde, etc.) de las celdas de Excel utilizando degradados lineales y rectangulares en las celdas. Cuando los libros con estos degradados se guardan en formato de archivo .xls y se abren en Microsoft Excel 2007/2010, los degradados serán visibles, pero cuando estos archivos se abren en Microsoft Excel 2003, la celda se rellenará con el color sólido desde el principio. parada de gradiente.
Estas son las formas en que se puede definir un color, de la siguiente manera:
El color automático (que es el color del sistema WindowText)
Cualquier color RGB definido por el usuario
A theme color
Si se utiliza un color RGB o de tema, se puede aplicar un tinte opcional para aclarar u oscurecer el color. Este tinte no se puede configurar directamente en la interfaz de usuario de Microsoft Excel 2007, pero varios colores en la paleta de colores que se muestra al usuario son en realidad colores de tema con tintes aplicados.
Cada libro tiene 12 colores temáticos asociados. Son los siguientes:
Light 1
Light 2
Dark 1
Dark 2
Accent1
Accent2
Accent3
Accent4
Accent5
Accent6
Hipervínculo
Followed Hyperlink
Hay valores predeterminados cuando se crea un libro, que se pueden personalizar a través de 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.
Al guardar en formatos de archivo más nuevos, como .xlsx, la información de color más nueva se guarda directamente en el archivo. Al guardar en un formato de archivo antiguo como .xls, se guardará el índice del color más cercano en la paleta. Además, los formatos más antiguos tienen registros de características futuras que se pueden guardar para indicar la información de color más nueva.
Cuando los formatos más antiguos se abren en Microsoft Excel 2003 y versiones anteriores, estos registros de características futuras se ignoran, pero cuando los formatos de archivos más antiguos se abren en Excel 2007 y versiones posteriores, sus registros se leen y la información de color de ellos sobrescribe el color indexado que se cargó previamente desde los registros en 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.
Cuando se elimina un indicador de opción de formato de un formato, todas las propiedades asociadas se restablecen a sus valores no establecidos, por lo que las propiedades del borde del formato de celda se restablecen implícitamente a sus valores predeterminados/no establecidos.
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
Además de establecer el valor o el formato de las celdas, también puedes fusionar celdas para que dos o más celdas parezcan una sola. Si combina celdas, deben estar en una región rectangular.
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.
Establecer el valor (o formato de celda) de la región o cualquier celda de la región cambiará el valor de todas las celdas y de la región. Si separa celdas, todas las celdas previamente combinadas conservarán el formato de celda compartida que tenían antes de separarlas. Sin embargo, solo la celda superior izquierda de la región conservará el valor compartido.
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
El texto que se muestra en una celda depende de varios factores además del valor real de la celda, como la cadena de formato y el ancho de la columna que contiene la celda.
La cadena de formato determina cómo se convierte el valor de la celda en texto y qué carácter literal se debe mostrar con el valor formateado. Puede encontrar información más detallada sobre los códigos de formato aquí.
La cantidad de espacio horizontal disponible en una celda juega un papel importante en cómo se muestra el valor al usuario.
El texto mostrado puede ser diferente según los distintos anchos de columna.
Al mostrar números y utilizar una cadena de formato que contenga "General" o"@", existen varios formatos que se intentan encontrar para encontrar un formato que se ajuste al ancho de la celda. A continuación se muestra una lista de formatos de ejemplo:
Valor normal: el número se muestra como sería si hubiera una cantidad ilimitada de espacio.
Eliminar dígitos decimales: los dígitos decimales se eliminarán uno a la vez hasta que se encuentre un formato que se ajuste. Por ejemplo, un valor de 12345,6789 se reducirá a los siguientes formatos hasta que uno quepa: 12345,679, 12345,68, 12345,7 y 12346. Esto se detendrá cuando el primer dígito significativo sea el único que quede, por lo que, por ejemplo, un valor como 0,0001234567890 solo se puede reducido a 0,0001.
Científico, 5 dígitos decimales: el número se muestra en forma de 0,00000E+00, como 1,23457E+09 o 1,23457E-04.
Científico, 4 dígitos decimales: el número se muestra en forma de 0,0000E+00, como 1,2346E+09 o 1,23456E-04.
Científico, 3 dígitos decimales: el número se muestra en forma de 0,000E+00, como 1,235E+09 o 1,235E-0.
Científico, 2 dígitos decimales: el número se muestra en forma de 0,00E+00, como 1,23E+09 o 1,23E-04.
Científico, 1 dígito decimal: el número se muestra en forma de 0,0E+00, como 1,2E+09 o 1,2E-04.
Científico, 0 dígitos decimales: el número se muestra en forma de 0E+00, como 1E+09 o 1E-04.
Valor redondeado: si el primer dígito significativo está en la parte decimal del número, el valor se redondeará al valor entero más cercano. Por ejemplo, para un valor 0,0001234567890, se redondeará a 0 y el texto mostrado en la celda será 0.
Marcas de almohadilla: si no se puede mostrar una versión condensada del número, las almohadillas (#) se repetirán en todo el ancho de la celda.
Cadena vacía: si no caben marcas hash en la celda, se devolverá una cadena vacía como texto de celda mostrado.
Si la cadena de formato para el valor numérico no contiene General o @, solo existen las siguientes etapas de cambio de tamaño: Valor normal, Marcas de almohadilla, Cadena vacía
Si se utiliza un texto en la celda, el texto mostrado en la celda siempre tendrá el valor completo, independientemente de si está cortado o no en la celda.
El único momento en el que este no es el caso es cuando se utilizan caracteres de relleno en la cadena de formato. Luego, el valor se mostrará como todas las marcas de almohadilla cuando no haya suficiente espacio para el 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 .
Además, si el valor no cabe, no se mostrará como todos los hashes. El texto mostrado seguirá devolviendo su texto completo como texto de la celda, aunque no se vea por completo.
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();