Establecer formatos condicionales de archivos Excel y ODS

Introducción

El formato condicional es una característica avanzada que permite aplicar formatos a una celda o rango de celdas y que ese formato cambie dependiendo del valor de la celda o del valor de una fórmula. Por ejemplo, puedes hacer que una celda aparezca en negrita solo cuando el valor de la celda sea mayor a 500. Cuando el valor de la celda cumple la condición, se aplica el formato especificado a la celda. Si el valor de la celda no cumple la condición, se usa el formato predeterminado de la celda. En Microsoft Excel, selecciona Formato, luego Formato condicional para abrir el cuadro de diálogo de Formato condicional.

Aspose.Cells admite aplicar formato condicional a las celdas en tiempo de ejecución. Este artículo explica cómo. También explica cómo calcular el color utilizado por Excel para el formato condicional de escala de color.

Aplicar formato condicional

Aspose.Cells admite el formato condicional de varias maneras:

  • Usando una hoja de cálculo de diseñador
  • Usando el método de copia.
  • Creando formato condicional en tiempo de ejecución.

Usar la Hoja de Cálculo de Diseñador

Los desarrolladores pueden crear una hoja de cálculo de diseñador que contenga formato condicional en Microsoft Excel y luego abrir esa hoja de cálculo con Aspose.Cells. Aspose.Cells carga y guarda la hoja de cálculo de diseñador, conservando cualquier configuración de formato condicional.

Usando el Método de Copia

Aspose.Cells permite a los desarrolladores copiar la configuración de formato condicional de una celda a otra en la hoja de cálculo llamando al método Range.copy().

const AsposeCells = require("aspose.cells.node");
const path = require("path");
// The path to the documents directory.
const dataDir = path.join(__dirname, "data");
// Open a template Excel file
const workbook = new AsposeCells.Workbook(path.join(dataDir, "book1.xlsx"));
// Get the first worksheet in the workbook
const sheet = workbook.getWorksheets().get(0);
// Get the A1 cell
const cell = sheet.getCells().get("A1");
// Get the conditional formatting result object
const cfr = cell.getConditionalFormattingResult();
// Get the icon set
const icon = cfr.getConditionalFormattingIcon();
// Create the image file based on the icon's image data
require("fs").writeFileSync(path.join(dataDir, "imgIcon.out.jpg"), icon.getImageData());

Aplicar formato condicional en tiempo de ejecución

Aspose.Cells te permite tanto agregar como eliminar formato condicional en tiempo de ejecución. Los ejemplos de código a continuación muestran cómo establecer el formato condicional:

  1. Instanciar un libro de trabajo.
  2. Agregar un formato condicional vacío.
  3. Establecer el rango al que debe aplicarse el formato.
  4. Definir las condiciones de formato.
  5. Guarde el archivo.

Después de este ejemplo vienen varios ejemplos más pequeños que muestran cómo aplicar configuraciones de fuente, configuraciones de bordes y patrones.

Microsoft Excel 2007 agregó un formato condicional más avanzado que también soporta Aspose.Cells. Los ejemplos aquí muestran cómo usar un formato sencillo, mientras que los ejemplos de Microsoft Excel 2007 muestran cómo aplicar un formato condicional más avanzado.

const AsposeCells = require("aspose.cells.node");
const path = require("path");
// The path to the documents directory.
const dataDir = path.join(__dirname, "data");
const filePath = path.join(dataDir, "Book1.xlsx");
// Instantiating a Workbook object
const workbook = new AsposeCells.Workbook();
const sheet = workbook.getWorksheets().get(0);
// Adds an empty conditional formatting
const index = sheet.getConditionalFormattings().getCount();
const fcs = sheet.getConditionalFormattings().get(index);
// Sets the conditional format range.
let ca = AsposeCells.CellArea.createCellArea(0, 0, 0, 0);
fcs.addArea(ca);
ca = AsposeCells.CellArea.createCellArea(1, 1, 1, 1);
fcs.addArea(ca);
// Adds condition.
const conditionIndex = fcs.addCondition(AsposeCells.FormatConditionType.CellValue, AsposeCells.OperatorType.Between, "=A2", "100");
// Adds condition.
const conditionIndex2 = fcs.addCondition(AsposeCells.FormatConditionType.CellValue, AsposeCells.OperatorType.Between, "50", "100");
// Sets the background color.
const fc = fcs.get(conditionIndex);
fc.getStyle().setBackgroundColor(AsposeCells.Color.Red);
// Saving the Excel file
workbook.save(path.join(dataDir, "output.xls"));

Establecer fuente

const AsposeCells = require("aspose.cells.node");
const path = require("path");
// The path to the documents directory.
const dataDir = path.join(__dirname, "data");
// Open a template Excel file
const workbook = new AsposeCells.Workbook(path.join(dataDir, "book1.xlsx"));
// Get the first worksheet in the workbook
const sheet = workbook.getWorksheets().get(0);
// Get the A1 cell
const cell = sheet.getCells().get("A1");
// Get the conditional formatting result object
const cfr = cell.getConditionalFormattingResult();
// Get the icon set
const icon = cfr.getConditionalFormattingIcon();
// Create the image file based on the icon's image data
require("fs").writeFileSync(path.join(dataDir, "imgIcon.out.jpg"), icon.getImageData());

Establecer borde

const path = require("path");
const AsposeCells = require("aspose.cells.node");
// The path to the documents directory.
const dataDir = path.join(__dirname, "data");
// Instantiating a Workbook object
const workbook = new AsposeCells.Workbook();
const sheet = workbook.getWorksheets().get(0);
// Adds an empty conditional formatting
const index = sheet.getConditionalFormattings().add();
const fcs = sheet.getConditionalFormattings().get(index);
// Sets the conditional format range.
const ca = AsposeCells.CellArea.createCellArea(0, 0, 5, 3);
fcs.addArea(ca);
// Adds condition.
const conditionIndex = fcs.addCondition(AsposeCells.FormatConditionType.CellValue, AsposeCells.OperatorType.Between, "50", "100");
// Sets the background color.
const fc = fcs.get(conditionIndex);
fc.getStyle().getBorders().get(AsposeCells.BorderType.LeftBorder).setLineStyle(AsposeCells.CellBorderType.Dashed);
fc.getStyle().getBorders().get(AsposeCells.BorderType.RightBorder).setLineStyle(AsposeCells.CellBorderType.Dashed);
fc.getStyle().getBorders().get(AsposeCells.BorderType.TopBorder).setLineStyle(AsposeCells.CellBorderType.Dashed);
fc.getStyle().getBorders().get(AsposeCells.BorderType.BottomBorder).setLineStyle(AsposeCells.CellBorderType.Dashed);
fc.getStyle().getBorders().get(AsposeCells.BorderType.LeftBorder).setColor(new AsposeCells.Color(0, 255, 255));
fc.getStyle().getBorders().get(AsposeCells.BorderType.RightBorder).setColor(new AsposeCells.Color(0, 255, 255));
fc.getStyle().getBorders().get(AsposeCells.BorderType.TopBorder).setColor(new AsposeCells.Color(0, 255, 255));
fc.getStyle().getBorders().get(AsposeCells.BorderType.BottomBorder).setColor(new AsposeCells.Color(255, 255, 0));
workbook.save(path.join(dataDir, "output.xlsx"));

Establecer patrón

const path = require("path");
const AsposeCells = require("aspose.cells.node");
// The path to the documents directory.
const dataDir = path.join(__dirname, "data");
// Instantiating a Workbook object
const workbook = new AsposeCells.Workbook();
const sheet = workbook.getWorksheets().get(0);
// Adds an empty conditional formatting
const index = sheet.getConditionalFormattings().add();
const fcs = sheet.getConditionalFormattings().get(index);
// Sets the conditional format range.
const ca = AsposeCells.CellArea.createCellArea(0, 0, 5, 3);
fcs.addArea(ca);
// Adds condition.
const conditionIndex = fcs.addCondition(AsposeCells.FormatConditionType.CellValue, AsposeCells.OperatorType.Between, "50", "100");
const fc = fcs.get(conditionIndex);
fc.getStyle().setPattern(AsposeCells.BackgroundType.ReverseDiagonalStripe);
fc.getStyle().setForegroundColor(new AsposeCells.Color(255, 255, 0));
fc.getStyle().setBackgroundColor(new AsposeCells.Color(0, 255, 255));
workbook.save(path.join(dataDir, "output.xlsx"));

Temas avanzados