Cómo agregar formato condicional de texto

Escenarios de uso posibles

Usar formato condicional basado en texto en hojas de cálculo es útil para resaltar celdas que cumplen con criterios textuales específicos. Esto puede mejorar el análisis de datos y facilitar la búsqueda de información clave en un conjunto de datos grande. Aquí algunas razones para usar formato condicional de texto:

  1. Resaltar Texto Específico: Puedes aplicar formato en función de palabras, frases o caracteres específicos. Por ejemplo, quizás quieras resaltar todas las celdas que contienen la palabra “Urgente” o “Completado” para diferenciar tareas en un proyecto fácilmente.
  2. Identificar patrones o tendencias: Si trabajas con categorías o estados (como “Alto”, “Medio”, “Bajo”), el formato condicional de texto puede distinguir visualmente entre ellos, facilitando el seguimiento del progreso o priorización de tareas.
  3. Alertas de errores o entrada de datos: El formato de texto puede marcar entradas inconsistentes o erróneas, como palabras mal escritas, texto incompleto o valores incorrectos. Esto es especialmente útil en conjuntos de datos con mucha entrada textual.
  4. Mejora de la legibilidad: Codificar por colores el texto o cambiar su estilo (negrita, cursiva, etc.) ayuda a que la información importante destaque, mejorando la legibilidad general de tu hoja.
  5. Retroalimentación dinámica: Puedes establecer reglas que ajusten automáticamente el formato cuando el texto coincida con ciertas condiciones. Esto significa que no tienes que actualizar manualmente el formato a medida que cambian los datos.

En esencia, el formato condicional de texto te ayuda a detectar rápidamente información relevante, errores y tendencias, convirtiéndolo en una herramienta poderosa para gestionar e interpretar datos textuales.

Cómo agregar formato condicional de texto usando Excel

Para agregar formato condicional basado en texto en Excel, sigue estos pasos:

  1. Selecciona el rango de celdas: Resalta las celdas donde deseas aplicar el formato condicional.
  2. Abre el menú de Formato condicional: Ve a la pestaña Inicio en la cinta de opciones de Excel. Haz clic en Formato condicional en el grupo “Estilos”.
  3. Elige “Nueva regla”: Desde el menú desplegable, selecciona Nueva regla.
  4. Selecciona “Formatear solo celdas que contengan”: En el cuadro de diálogo Nueva regla de formato, elige Formatear solo celdas que contengan en la sección “Seleccionar un tipo de regla”.
  5. Establece los criterios de la regla: En la sección “Formatear celdas con”, elige Texto específico en el menú desplegable. Selecciona si contiene, empieza con o termina con, dependiendo de la condición que deseas aplicar. Ingresa el texto que quieres formatear (por ejemplo, una palabra específica como “Urgente” o “Completado”).
  6. Elige el formato: Haz clic en el botón de Formato. En el cuadro de diálogo de Formato de celdas, puedes seleccionar el color de fuente, color de relleno u otras opciones de formato que prefieras.
  7. Aplica la regla: Una vez que hayas establecido el formato deseado, haz clic en Aceptar para aplicar la regla. Haz clic en Aceptar nuevamente en el cuadro de diálogo Nueva regla de formato para cerrarlo.
  8. Ver los resultados: Las celdas que contienen el texto especificado tendrán ahora el formato aplicado, facilitando la identificación de la información relevante.

Cómo agregar formato condicional de texto usando Aspose.Cells for .NET

Aspose.Cells admite completamente el formato condicional proporcionado por Microsoft Excel 2007 y versiones posteriores en formato XLSX en las celdas en tiempo de ejecución. Estos ejemplos demuestran un ejercicio de formatos condicionales avanzados incluyendo BeginsWith, ContainsBlank, ContainsText, etc.

Formate la celda cuando el valor comience con texto especificado

// This method implements the BeginsWith conditional formatting type.
private void AddBeginWith()
{
// Instantiate a workbook object
Workbook book = new Workbook();
// Create a worksheet object and get the first worksheet
Worksheet _sheet = book.Worksheets[0];
FormatConditionCollection conds = GetFormatCondition("E15:G16", Color.LightGoldenrodYellow, _sheet);
int idx = conds.AddCondition(FormatConditionType.BeginsWith);
FormatCondition cond = conds[idx];
cond.Style.BackgroundColor = Color.Pink;
cond.Style.Pattern = BackgroundType.Solid;
cond.Text = "ab";
Cell c = _sheet.Cells["E15"];
c.PutValue("abc");
c = _sheet.Cells["G16"];
c.PutValue("babx");
book.Save("BeginsWith.xlsx");
}
// This method adds formatted conditions.
private FormatConditionCollection GetFormatCondition(string cellAreaName, Color color, Worksheet _sheet)
{
// Adds an empty conditional formattings
int index = _sheet.ConditionalFormattings.Add();
// Get the formatted conditions
FormatConditionCollection formatConditions = _sheet.ConditionalFormattings[index];
// Get the cell area calling the custom GetCellAreaByName method
CellArea area = GetCellAreaByName(cellAreaName);
// Add the formatted conditions cell area.
formatConditions.AddArea(area);
// Call the custom FillCell method
FillCell(cellAreaName, color, _sheet);
// Return the formatted conditions
return formatConditions;
}
// This method specifies the cell shading color for the conditional formattings cellarea range.
private void FillCell(string cellAreaName, Color color, Worksheet _sheet)
{
CellArea area = GetCellAreaByName(cellAreaName);
int k = 0;
for (int i = area.StartColumn; i <= area.EndColumn; i++)
{
for (int j = area.StartRow; j <= area.EndRow; j++)
{
Cell c = _sheet.Cells[j, i];
if (!color.IsEmpty)
{
Style s = c.GetStyle();
s.ForegroundColor = color;
s.Pattern = BackgroundType.Solid;
c.SetStyle(s);
}
// Set some random values to the cells in the cellarea range
int value = j + i + k;
c.PutValue(value);
k++;
}
}
}
// This method specifies the CellArea range (start row, start col, end row, end col etc.)
// For the conditional formatting
internal static CellArea GetCellAreaByName(string s)
{
CellArea area = new CellArea();
string[] strCellRange = s.Replace("$", "").Split(':');
int column;
CellsHelper.CellNameToIndex(strCellRange[0], out area.StartRow, out column);
area.StartColumn = column;
if (strCellRange.Length == 1)
{
area.EndRow = area.StartRow;
area.EndColumn = area.StartColumn;
}
else
{
CellsHelper.CellNameToIndex(strCellRange[1], out area.EndRow, out column);
area.EndColumn = column;
}
return area;
}

Formate la celda cuando el valor contenga en blanco

// This method implements the ContainsBlank conditional formatting type.
private void AddContainsBlank()
{
// Instantiate a workbook object
Workbook book = new Workbook();
// Create a worksheet object and get the first worksheet
Worksheet _sheet = book.Worksheets[0];
FormatConditionCollection conds = GetFormatCondition("E9:G10", Color.LightBlue, _sheet);
int idx = conds.AddCondition(FormatConditionType.ContainsBlanks);
FormatCondition cond = conds[idx];
cond.Style.BackgroundColor = Color.Yellow;
cond.Style.Pattern = BackgroundType.Solid;
Cell c = _sheet.Cells["E9"];
c.PutValue(" ");
c = _sheet.Cells["G10"];
c.PutValue(" ");
book.Save("ContainsBlank.xlsx");
}

Formate la celda cuando el valor contenga errores

// This method implements the ContainsErrors conditional formatting type.
private void AddContainsErrors()
{
// Instantiate a workbook object
Workbook book = new Workbook();
// Create a worksheet object and get the first worksheet
Worksheet _sheet = book.Worksheets[0];
FormatConditionCollection conds = GetFormatCondition("E17:G18", Color.LightSkyBlue, _sheet);
int idx = conds.AddCondition(FormatConditionType.ContainsErrors);
FormatCondition cond = conds[idx];
cond.Style.BackgroundColor = Color.Yellow;
cond.Style.Pattern = BackgroundType.Solid;
Cell c = _sheet.Cells["E17"];
c.PutValue(" ");
c = _sheet.Cells["G18"];
c.PutValue(" ");
book.Save("ContainsErrors.xlsx");
}

Formate la celda cuando el valor contenga texto especificado

// This method implements the ContainsText conditional formatting type.
private void AddContainsText()
{
// Instantiate a workbook object
Workbook book = new Workbook();
// Create a worksheet object and get the first worksheet
Worksheet _sheet = book.Worksheets[0];
FormatConditionCollection conds = GetFormatCondition("E5:G6", Color.LightBlue, _sheet);
int idx = conds.AddCondition(FormatConditionType.ContainsText);
FormatCondition cond = conds[idx];
cond.Style.BackgroundColor = Color.Yellow;
cond.Style.Pattern = BackgroundType.Solid;
cond.Text = "1";
book.Save("ContainsText.xlsx");
}

Formate la celda cuando el valor contenga valores duplicados

// This method implements the DuplicateValues conditional formatting type.
private void AddDuplicateValues()
{
// Instantiate a workbook object
Workbook book = new Workbook();
// Create a worksheet object and get the first worksheet
Worksheet _sheet = book.Worksheets[0];
FormatConditionCollection conds = GetFormatCondition("E23:G24", Color.LightSlateGray, _sheet);
int idx = conds.AddCondition(FormatConditionType.DuplicateValues);
FormatCondition cond = conds[idx];
cond.Style.BackgroundColor = Color.Pink;
cond.Style.Pattern = BackgroundType.Solid;
Cell c = _sheet.Cells["E23"];
c.PutValue("bb");
c = _sheet.Cells["G24"];
c.PutValue("bb");
book.Save("DuplicateValues.xlsx");
}

Formate la celda cuando el valor termine con texto especificado

// This method implements the EndsWith conditional formatting type.
private void AddEndWith()
{
// Instantiate a workbook object
Workbook book = new Workbook();
// Create a worksheet object and get the first worksheet
Worksheet _sheet = book.Worksheets[0];
FormatConditionCollection conds = GetFormatCondition("E13:G14", Color.LightGray, _sheet);
int idx = conds.AddCondition(FormatConditionType.EndsWith);
FormatCondition cond = conds[idx];
cond.Style.BackgroundColor = Color.Yellow;
cond.Style.Pattern = BackgroundType.Solid;
cond.Text = "ab";
Cell c = _sheet.Cells["E13"];
c.PutValue("nnnab");
c = _sheet.Cells["G14"];
c.PutValue("mmmabc");
book.Save("EndsWith.xlsx");
}

Formate la celda cuando el valor no contenga en blanco

// This method implements the NotContainsBlank conditional formatting type.
private void AddNotContainsBlank()
{
// Instantiate a workbook object
Workbook book = new Workbook();
// Create a worksheet object and get the first worksheet
Worksheet _sheet = book.Worksheets[0];
FormatConditionCollection conds = GetFormatCondition("E11:G12", Color.LightCoral, _sheet);
int idx = conds.AddCondition(FormatConditionType.NotContainsBlanks);
FormatCondition cond = conds[idx];
cond.Style.BackgroundColor = Color.Pink;
cond.Style.Pattern = BackgroundType.Solid;
Cell c = _sheet.Cells["E11"];
c.PutValue("abc");
c = _sheet.Cells["G12"];
c.PutValue(" ");
book.Save("NotContainsBlank.xlsx");
}

Formate la celda cuando el valor no contenga errores

// This method implements the NotContainsErrors conditional formatting type.
private void AddNotContainsErrors()
{
// Instantiate a workbook object
Workbook book = new Workbook();
// Create a worksheet object and get the first worksheet
Worksheet _sheet = book.Worksheets[0];
FormatConditionCollection conds = GetFormatCondition("E19:G20", Color.LightSeaGreen, _sheet);
int idx = conds.AddCondition(FormatConditionType.NotContainsErrors);
FormatCondition cond = conds[idx];
cond.Style.BackgroundColor = Color.Pink;
cond.Style.Pattern = BackgroundType.Solid;
Cell c = _sheet.Cells["E19"];
c.PutValue(" ");
c = _sheet.Cells["G20"];
c.PutValue(" ");
book.Save("NotContainsErrors.xlsx");
}

Formate la celda cuando el valor no contenga texto especificado

// This method implements the NotContainsText conditional formatting type.
private void AddNotContainsText()
{
// Instantiate a workbook object
Workbook book = new Workbook();
// Create a worksheet object and get the first worksheet
Worksheet _sheet = book.Worksheets[0];
FormatConditionCollection conds = GetFormatCondition("E7:G8", Color.LightCoral, _sheet);
int idx = conds.AddCondition(FormatConditionType.NotContainsText);
FormatCondition cond = conds[idx];
cond.Style.BackgroundColor = Color.Pink;
cond.Style.Pattern = BackgroundType.Solid;
cond.Text = "3";
book.Save("NotContainsText.xlsx");
}

Formate la celda cuando el valor contenga valores únicos

// This method implements the UniqueValues conditional formatting type.
private void AddUniqueValues()
{
// Instantiate a workbook object
Workbook book = new Workbook();
// Create a worksheet object and get the first worksheet
Worksheet _sheet = book.Worksheets[0];
FormatConditionCollection conds = GetFormatCondition("E21:G22", Color.LightSalmon, _sheet);
int idx = conds.AddCondition(FormatConditionType.UniqueValues);
FormatCondition cond = conds[idx];
cond.Style.BackgroundColor = Color.Yellow;
cond.Style.Pattern = BackgroundType.Solid;
Cell c = _sheet.Cells["E21"];
c.PutValue("aa");
c = _sheet.Cells["G22"];
c.PutValue("aa");
book.Save("UniqueValues.xlsx");
}