Aplicar estilos a tablas dinámicas en Aspose.Cells for C++

Introducción

Aspose.Cells expone dos API de estilos paralelas para tablas dinámicas. La decisión entre ellas depende del formato de archivo en el que guarda el libro de trabajo, no del formato desde el que lo lee. Un libro de trabajo cargado desde un archivo .xls puede volver a guardarse como .xlsx, y en ese caso se aplica la API de estilos moderna en lugar de la heredada.

  • PivotTable.PivotTableStyleType selecciona uno de los estilos con nombre integrados (temas claros y oscuros, incluidos los estilos añadidos en Excel 2017). Estos preajustes son de solo lectura.
  • PivotTable.PivotTableStyleName selecciona un estilo personalizado que defina usted mismo mediante Worksheets.TableStyles.AddPivotTableStyle(...). Los estilos personalizados son necesarios cuando desea modificar colores, bordes o fuentes más allá de lo que ofrecen los preajustes. Además, PivotTable.FormatAll(Style) es un atajo que aplica un único objeto Style a cada celda de la tabla dinámica, anulando lo que esté establecido mediante cualquiera de las API de nombres de estilo anteriores. Esto resulta útil cuando se requiere una apariencia uniforme independientemente del tema subyacente.

Aplicar un autoformato preajustado XLS heredado

PivotTable.AutoFormatType acepta un valor de la enumeración Aspose.Cells.Pivot.PivotTableAutoFormatType. Los valores disponibles son Report1 a Report10, Classic, y Table1 a Table10. El siguiente ejemplo carga un libro de trabajo nuevo, rellena los datos de muestra Fruta/Año/Cantidad, añade una tabla dinámica, aplica PivotTableAutoFormatType.Report5 y guarda el resultado como .xls.

#include "Aspose.Cells.h"
using namespace Aspose::Cells;
using namespace Aspose::Cells::Pivot;
int main() {
    Aspose::Cells::Startup();
    // Crear un nuevo libro de trabajo
    Workbook workbook;
    // Obtener la primera hoja de trabajo
    Worksheet sheet = workbook.GetWorksheets().Get(0);
    // Rellenar los datos de origen con fila de encabezado (Fruit, Year, Amount)
    // y 9 filas de datos cubriendo grape, blueberry, kiwi, cherry en 2020 y 2021
    sheet.GetCells().Get(0, 0).PutValue(u"Fruit");
    sheet.GetCells().Get(0, 1).PutValue(u"Year");
    sheet.GetCells().Get(0, 2).PutValue(u"Amount");
    sheet.GetCells().Get(1, 0).PutValue(u"grape");
    sheet.GetCells().Get(1, 1).PutValue(2020);
    sheet.GetCells().Get(1, 2).PutValue(50);
    sheet.GetCells().Get(2, 0).PutValue(u"blueberry");
    sheet.GetCells().Get(2, 1).PutValue(2020);
    sheet.GetCells().Get(2, 2).PutValue(30);
    sheet.GetCells().Get(3, 0).PutValue(u"kiwi");
    sheet.GetCells().Get(3, 1).PutValue(2020);
    sheet.GetCells().Get(3, 2).PutValue(25);
    sheet.GetCells().Get(4, 0).PutValue(u"cherry");
    sheet.GetCells().Get(4, 1).PutValue(2020);
    sheet.GetCells().Get(4, 2).PutValue(40);
    sheet.GetCells().Get(5, 0).PutValue(u"grape");
    sheet.GetCells().Get(5, 1).PutValue(2021);
    sheet.GetCells().Get(5, 2).PutValue(60);
    sheet.GetCells().Get(6, 0).PutValue(u"blueberry");
    sheet.GetCells().Get(6, 1).PutValue(2021);
    sheet.GetCells().Get(6, 2).PutValue(35);
    sheet.GetCells().Get(7, 0).PutValue(u"kiwi");
    sheet.GetCells().Get(7, 1).PutValue(2021);
    sheet.GetCells().Get(7, 2).PutValue(28);
    sheet.GetCells().Get(8, 0).PutValue(u"cherry");
    sheet.GetCells().Get(8, 1).PutValue(2021);
    sheet.GetCells().Get(8, 2).PutValue(45);
    sheet.GetCells().Get(9, 0).PutValue(u"grape");
    sheet.GetCells().Get(9, 1).PutValue(2020);
    sheet.GetCells().Get(9, 2).PutValue(45);
 // Agregar una tabla dinámica en la celda destino E3, llamada, usando el rango de origen A1:C10
    PivotTable pivotTable = sheet.GetPivotTables().Add(u"A1:C10", 2, 4);
    // Asignar campos: Fruit -> Filas, Amount -> Datos
    pivotTable.AddFieldToArea(PivotFieldType::Row, u"Fruit");
    pivotTable.AddFieldToArea(PivotFieldType::Data, u"Amount");
    // Aplicar el formato automático preestablecido heredado de XLS "Report5"
    pivotTable.SetAutoFormatType(PivotTableAutoFormatType::Report5);
    // Guardar el libro de trabajo en formato .xls heredado
    workbook.Save(u"output.xls");
    Aspose::Cells::Cleanup();
    return 0;
}

Aplicar un estilo de tabla dinámica preajustado con nombre moderno

SetPivotTableStyleType selecciona uno de los estilos integrados con nombre que Excel 2007 introdujo para las tablas dinámicas. La enumeración PivotTableStyleType expone tres familias de temas: la familia clara desde PivotTableStyleLight1 hasta PivotTableStyleLight28, la familia media desde PivotTableStyleMedium1 hasta PivotTableStyleMedium28 y la familia oscura desde PivotTableStyleDark1 hasta PivotTableStyleDark28. También define None y Custom. Los miembros con números más altos de cada familia son los estilos agregados en Excel 2017. Estos preajustes son de solo lectura. En cuanto necesite cambiar colores, bordes o fuentes más allá de lo que ofrece un preajuste, tendrá que definir en su lugar un estilo personalizado para tablas dinámicas, como se muestra en Escenario 3.

Este escenario reutiliza el conjunto de datos Fruit/Year/Amount del Escenario 1, agrega Year al área de columnas junto con el campo de fila Fruit mediante PivotFieldType::Column, aplica el preajuste de tema oscuro PivotTableStyleDark1 con SetPivotTableStyleType y guarda el resultado como .xlsx — el formato para el cual PivotTableStyleType es válido.

#include "Aspose.Cells.h"
using namespace Aspose::Cells;
using namespace Aspose::Cells::Pivot;
int main() {
    Aspose::Cells::Startup();
    Workbook workbook;
    Worksheet worksheet = workbook.GetWorksheets().Get(0);
    Cells cells = worksheet.GetCells();
    cells.Get(u"A1").PutValue(u"Fruit");
    cells.Get(u"B1").PutValue(u"Year");
    cells.Get(u"C1").PutValue(u"Amount");
    cells.Get(u"A2").PutValue(u"Grape");
    cells.Get(u"B2").PutValue(2020);
    cells.Get(u"C2").PutValue(100);
    cells.Get(u"A3").PutValue(u"Blueberry");
    cells.Get(u"B3").PutValue(2020);
    cells.Get(u"C3").PutValue(150);
    cells.Get(u"A4").PutValue(u"Kiwi");
    cells.Get(u"B4").PutValue(2020);
    cells.Get(u"C4").PutValue(200);
    cells.Get(u"A5").PutValue(u"Cherry");
    cells.Get(u"B5").PutValue(2020);
    cells.Get(u"C5").PutValue(180);
    cells.Get(u"A6").PutValue(u"Grape");
    cells.Get(u"B6").PutValue(2021);
    cells.Get(u"C6").PutValue(120);
    cells.Get(u"A7").PutValue(u"Blueberry");
    cells.Get(u"B7").PutValue(2021);
    cells.Get(u"C7").PutValue(170);
    cells.Get(u"A8").PutValue(u"Kiwi");
    cells.Get(u"B8").PutValue(2021);
    cells.Get(u"C8").PutValue(210);
    cells.Get(u"A9").PutValue(u"Cherry");
    cells.Get(u"B9").PutValue(2021);
    cells.Get(u"C9").PutValue(190);
    cells.Get(u"A10").PutValue(u"Grape");
    cells.Get(u"B10").PutValue(2021);
    cells.Get(u"C10").PutValue(130);
    PivotTable pivotTable = worksheet.GetPivotTables().Add(u"A1:C10", 2, 4);
    pivotTable.AddFieldToArea(PivotFieldType::Row, u"Fruit");
    pivotTable.AddFieldToArea(PivotFieldType::Column, u"Year");
    pivotTable.AddFieldToArea(PivotFieldType::Data, u"Amount");
    pivotTable.SetPivotTableStyleType(PivotTableStyleType::PivotTableStyleDark1);
    workbook.Save(u"output.xlsx");
    Aspose::Cells::Cleanup();
    return 0;
}

Definir y aplicar un estilo personalizado de tabla dinámica

Los preajustes integrados no se pueden modificar. Siempre que necesite anular colores, bordes o fuentes, debe definir un estilo personalizado de tabla dinámica. El flujo de trabajo consta de tres pasos:

  1. Añada un estilo personalizado a la colección TableStyles del libro de trabajo mediante Worksheets.TableStyles.AddPivotTableStyle(string name). Esto devuelve el índice del estilo recién creado.
  2. Configure el estilo añadiendo elementos (como WholeTable o GrandTotalRow) mediante TableStyle.TableStyleElements.Add(TableStyleElementType), y luego asigne un Style a cada elemento mediante TableStyleElement.SetElementStyle(Style).
  3. Aplique el estilo personalizado a la tabla dinámica asignando a PivotTable.PivotTableStyleName el nombre del estilo. No use aquí PivotTableStyleType, ya que esa propiedad selecciona preajustes integrados.
#include "Aspose.Cells.h"
using namespace Aspose::Cells;
using namespace Aspose::Cells::Pivot;
int main() {
    Aspose::Cells::Startup();
    Workbook workbook;
    Worksheet worksheet = workbook.GetWorksheets().Get(0);
    Cells cells = worksheet.GetCells();
    // Poblar datos fuente: fila de encabezado + 9 filas de datos (A1:C10)
    cells.Get(u"A1").PutValue(u"Fruit");
    cells.Get(u"B1").PutValue(u"Year");
    cells.Get(u"C1").PutValue(u"Amount");
    cells.Get(u"A2").PutValue(u"Grape");
    cells.Get(u"B2").PutValue(2020);
    cells.Get(u"C2").PutValue(100);
    cells.Get(u"A3").PutValue(u"Blueberry");
    cells.Get(u"B3").PutValue(2020);
    cells.Get(u"C3").PutValue(200);
    cells.Get(u"A4").PutValue(u"Kiwi");
    cells.Get(u"B4").PutValue(2020);
    cells.Get(u"C4").PutValue(300);
    cells.Get(u"A5").PutValue(u"Cherry");
    cells.Get(u"B5").PutValue(2020);
    cells.Get(u"C5").PutValue(400);
    cells.Get(u"A6").PutValue(u"Grape");
    cells.Get(u"B6").PutValue(2021);
    cells.Get(u"C6").PutValue(500);
    cells.Get(u"A7").PutValue(u"Blueberry");
    cells.Get(u"B7").PutValue(2021);
    cells.Get(u"C7").PutValue(600);
    cells.Get(u"A8").PutValue(u"Kiwi");
    cells.Get(u"B8").PutValue(2021);
    cells.Get(u"C8").PutValue(700);
    cells.Get(u"A9").PutValue(u"Cherry");
    cells.Get(u"B9").PutValue(2021);
    cells.Get(u"C9").PutValue(800);
    cells.Get(u"A10").PutValue(u"Grape");
    cells.Get(u"B10").PutValue(2021);
    cells.Get(u"C10").PutValue(900);
 // Agregar tabla dinámica con origen en A1:C10, anclada en E3, llamada
    PivotTable pivotTable = worksheet.GetPivotTables().Add(u"A1:C10", 2, 4);
    pivotTable.AddFieldToArea(PivotFieldType::Row, u"Fruit");
    pivotTable.AddFieldToArea(PivotFieldType::Column, u"Year");
    pivotTable.AddFieldToArea(PivotFieldType::Data, u"Amount");
    // Paso 1: registrar un nuevo estilo personalizado de tabla dinámica y capturar su índice
    int styleIndex = workbook.GetWorksheets().GetTableStyles().AddPivotTableStyle(u"CustomPivotStyle");
    TableStyle tableStyle = workbook.GetWorksheets().GetTableStyles().Get(styleIndex);
    // Paso 2: agregar un elemento WholeTable y aplicar bordes negros finos en los cuatro lados
    int wholeTableElementIndex = tableStyle.GetTableStyleElements().Add(TableStyleElementType::WholeTable);
    TableStyleElement wholeTableElement = tableStyle.GetTableStyleElements().Get(wholeTableElementIndex);
    Style wholeTableStyle = workbook.CreateStyle();
    wholeTableStyle.GetBorders().Get(BorderType::TopBorder).SetLineStyle(CellBorderType::Thin);
    wholeTableStyle.GetBorders().Get(BorderType::TopBorder).SetColor(Color::Black());
    wholeTableStyle.GetBorders().Get(BorderType::BottomBorder).SetLineStyle(CellBorderType::Thin);
    wholeTableStyle.GetBorders().Get(BorderType::BottomBorder).SetColor(Color::Black());
    wholeTableStyle.GetBorders().Get(BorderType::LeftBorder).SetLineStyle(CellBorderType::Thin);
    wholeTableStyle.GetBorders().Get(BorderType::LeftBorder).SetColor(Color::Black());
    wholeTableStyle.GetBorders().Get(BorderType::RightBorder).SetLineStyle(CellBorderType::Thin);
    wholeTableStyle.GetBorders().Get(BorderType::RightBorder).SetColor(Color::Black());
    wholeTableElement.SetElementStyle(wholeTableStyle);
    // Paso 3: agregar un elemento GrandTotalRow y aplicar fuente roja en negrita
    int grandTotalElementIndex = tableStyle.GetTableStyleElements().Add(TableStyleElementType::GrandTotalRow);
    TableStyleElement grandTotalElement = tableStyle.GetTableStyleElements().Get(grandTotalElementIndex);
    Style grandTotalStyle = workbook.CreateStyle();
    grandTotalStyle.GetFont().SetIsBold(true);
    grandTotalStyle.GetFont().SetColor(Color::Red());
    grandTotalElement.SetElementStyle(grandTotalStyle);
    // Paso 4: aplicar el estilo personalizado por nombre (NO por PivotTableStyleType, que es para preajustes integrados)
    pivotTable.SetPivotTableStyleName(u"CustomPivotStyle");
    workbook.Save(u"output.xlsx");
    Aspose::Cells::Cleanup();
    return 0;
}

Aplicar un solo estilo a cada celda de la tabla dinámica con FormatAll

PivotTable.FormatAll(Style) es un atajo que aplica un único objeto Style a cada celda de la tabla dinámica, incluido el área de datos, los encabezados de filas y columnas, y los totales. Lo que se haya establecido previamente mediante PivotTableStyleType o PivotTableStyleName queda anulado.

#include "Aspose.Cells.h"
#include <string>
using namespace Aspose::Cells;
using namespace Aspose::Cells::Pivot;
int main() {
    Aspose::Cells::Startup();
    Workbook wb;
    Worksheet worksheet = wb.GetWorksheets().Get(0);
    // Fila de encabezado
    worksheet.GetCells().Get(u"A1").PutValue(u"Fruit");
    worksheet.GetCells().Get(u"B1").PutValue(u"Year");
    worksheet.GetCells().Get(u"C1").PutValue(u"Amount");
    // Filas de datos
    worksheet.GetCells().Get(u"A2").PutValue(u"Grape");
    worksheet.GetCells().Get(u"B2").PutValue(2020);
    worksheet.GetCells().Get(u"C2").PutValue(5000);
    worksheet.GetCells().Get(u"A3").PutValue(u"Blueberry");
    worksheet.GetCells().Get(u"B3").PutValue(2020);
    worksheet.GetCells().Get(u"C3").PutValue(3000);
    worksheet.GetCells().Get(u"A4").PutValue(u"Kiwi");
    worksheet.GetCells().Get(u"B4").PutValue(2020);
    worksheet.GetCells().Get(u"C4").PutValue(4000);
    worksheet.GetCells().Get(u"A5").PutValue(u"Cherry");
    worksheet.GetCells().Get(u"B5").PutValue(2020);
    worksheet.GetCells().Get(u"C5").PutValue(2000);
    worksheet.GetCells().Get(u"A6").PutValue(u"Grape");
    worksheet.GetCells().Get(u"B6").PutValue(2021);
    worksheet.GetCells().Get(u"C6").PutValue(6000);
    worksheet.GetCells().Get(u"A7").PutValue(u"Blueberry");
    worksheet.GetCells().Get(u"B7").PutValue(2021);
    worksheet.GetCells().Get(u"C7").PutValue(3500);
    worksheet.GetCells().Get(u"A8").PutValue(u"Kiwi");
    worksheet.GetCells().Get(u"B8").PutValue(2021);
    worksheet.GetCells().Get(u"C8").PutValue(4500);
    worksheet.GetCells().Get(u"A9").PutValue(u"Cherry");
    worksheet.GetCells().Get(u"B9").PutValue(2021);
    worksheet.GetCells().Get(u"C9").PutValue(2500);
    worksheet.GetCells().Get(u"A10").PutValue(u"Grape");
    worksheet.GetCells().Get(u"B10").PutValue(2021);
    worksheet.GetCells().Get(u"C10").PutValue(5500);
 // Agregar tabla dinámica: rango de origen A1:C10, celda de destino E3, nombre
    PivotTable pivotTable = worksheet.GetPivotTables().Add(u"A1:C10", 2, 4);
    // Asignar campos dinámicos
    pivotTable.AddFieldToArea(PivotFieldType::Row, u"Fruit");
    pivotTable.AddFieldToArea(PivotFieldType::Column, u"Year");
    pivotTable.AddFieldToArea(PivotFieldType::Data, u"Amount");
    // Crear un estilo que se aplicará a cada celda de la tabla dinámica
    Style style = wb.CreateStyle();
    style.SetForegroundColor(Color::Yellow());
    style.SetPattern(BackgroundType::Solid);
    style.GetFont().SetIsBold(true);
    style.GetFont().SetColor(Color::DarkBlue());
    style.GetBorders().Get(BorderType::TopBorder).SetLineStyle(CellBorderType::Thin);
    style.GetBorders().Get(BorderType::TopBorder).SetColor(Color::Black());
    style.GetBorders().Get(BorderType::BottomBorder).SetLineStyle(CellBorderType::Thin);
    style.GetBorders().Get(BorderType::BottomBorder).SetColor(Color::Black());
    style.GetBorders().Get(BorderType::LeftBorder).SetLineStyle(CellBorderType::Thin);
    style.GetBorders().Get(BorderType::LeftBorder).SetColor(Color::Black());
    style.GetBorders().Get(BorderType::RightBorder).SetLineStyle(CellBorderType::Thin);
    style.GetBorders().Get(BorderType::RightBorder).SetColor(Color::Black());
    // Aplicar FormatAll
    pivotTable.FormatAll(style);
    // Guardar el libro
    wb.Save(u"output.xlsx");
    Aspose::Cells::Cleanup();
    return 0;
}

¿Qué API de estilo debo usar?

La elección de la API de estilo depende del formato de archivo en el que va a guardar. Use la tabla siguiente como referencia rápida.

Formato de archivo de destino API a usar Notas
.xls (heredado) PivotTable.AutoFormatType Valores de Aspose.Cells.Pivot.PivotTableAutoFormatType (por ejemplo, Report1–Report10, Classic, Table1–Table10). Se ignora al guardar en formatos modernos.
.xlsx / .xlsm / .xlsb (moderno, estilo integrado) PivotTable.PivotTableStyleType Valores de Aspose.Cells.PivotTableStyleType (temas claros/oscuros, incluidas las adiciones de Excel 2017).
.xlsx / .xlsm / .xlsb (moderno, estilo personalizado) PivotTable.PivotTableStyleName + Worksheets.TableStyles.AddPivotTableStyle(...) Úselo cuando los preajustes integrados no sean suficientes. Configure mediante TableStyleElement.SetElementStyle(...).
Cualquier formato (anulación uniforme) PivotTable.FormatAll(Style) Atajo que anula cualquier otra configuración de estilo en toda la tabla dinámica.
En caso de duda, guarde como .xlsx y use PivotTableStyleType para temas integrados, o PivotTableStyleName para temas personalizados.cpp