¿Cómo crear una tabla dinámica en Excel usando Java?

Se necesita una tabla dinámica para analizar rápidamente los datos de una tabla con muy poco esfuerzo (y sin fórmulas) y, a veces, no todos tienen tiempo para mirar los datos en la tabla y ver qué está pasando y usarlos para crear informes atractivos para grandes conjuntos de datos en una hoja de cálculo de Excel. analicemos una explicación adecuada paso a paso para crear una tabla dinámica en un archivo de Excel en Java utilizando Free Spire.XLS para la API de Java.

Implementación paso a paso

Paso 1: en primer lugar, debe agregar las dependencias necesarias en el proyecto maven para incluir el proyecto Free Spire.XLS antes de comenzar a escribir el código.

XML

<repositories> 
  <repository>
    <id>com.e-iceblue</id>
    <name>e-iceblue</name> 
    <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url> 
  </repository>  
</repositories> 
  
<dependencies>
  <dependency> 
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version> </dependency>
  <dependency>  
    <groupId>e-iceblue</groupId>  
    <artifactId>spire.xls.free</artifactId> 
    <version>3.9.1</version>
  </dependency>
</dependencies>   

Paso 2: Crear un libro de trabajo 

Workbook workbook = new Workbook();

Paso 3: Crea una hoja 

Worksheet sheet = workbook.getWorksheets().get(0);

Paso 4: agregue algunos datos a la hoja de trabajo en forma de tabla.

sheet.getCellRange("A1").setValue("Student Name");

Paso 5: Pivot Cache es algo que se genera automáticamente cuando crea una tabla dinámica. Cree un objeto de PivotCache y agregue un rango.

PivotCache cache = workbook.getPivotCaches().add(dataRange);

Paso 6: cree un objeto de tabla dinámica para obtener la tabla dinámica y agregue el nombre de la tabla, el rango de celdas desde donde comienza una tabla hasta arg1, PivotCache arg2

PivotTable pivotTable = sheet.getPivotTables().add("Pivot Table", sheet.getCellRange("A16"), cache);

Paso 7: cree un campo dinámico para configurar los campos de la tabla dinámica después de establecer el diseño de la tabla dinámica mediante el método setAxis y luego seleccione el tipo. 

PivotField pivotField1 = null;
if (pivotTable.getPivotFields().get("Student Name") instanceof PivotField) {
  pivotField1 = (PivotField) pivotTable.getPivotFields().get("Student Name");
 }
 pivotField1.setAxis(AxisTypes.Row);

Paso 8: arrastre el campo al área de datos

pivotTable.getDataFields().add(pivotTable.getPivotFields().get("Attendance"), "SUM of Attendance", SubtotalTypes.Sum);

Paso 9: establecer el estilo de tabla dinámica

pivotTable.setBuiltInStyle(PivotBuiltInStyles.PivotStyleMedium12);

Paso 10: Calcular datos

pivotTable.calculateData();

Paso 11: establezca el ancho de columna con el método setColumnWidth que tiene dos parámetros primero, columnIndex en tipo de datos int, tamaño de ancho en tipo de datos doble.

sheet.setColumnWidth(1, 14);
sheet.setColumnWidth(2, 14);

Paso 12: guarde el libro de trabajo usando saveToFile (String fileName, ExcelVersion version)

workbook.saveToFile(workbookName, ExcelVersion.Version2013);

Escribamos un programa Java para crear una tabla dinámica en una hoja de cálculo.

Java

import com.spire.xls.AxisTypes;
import com.spire.xls.CellRange;
import com.spire.xls.ExcelVersion;
import com.spire.xls.PivotBuiltInStyles;
import com.spire.xls.PivotCache;
import com.spire.xls.PivotField;
import com.spire.xls.PivotTable;
import com.spire.xls.SubtotalTypes;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Create a workbook
        Workbook workbook = new Workbook();
  
        // Create a sheet
        Worksheet sheet = workbook.getWorksheets().get(0);
        // Add data to the worksheet in table form
  
        // Header
        sheet.getCellRange("A1").setValue("Student Name");
        sheet.getCellRange("B1").setValue("Month");
        sheet.getCellRange("C1").setValue("Attendance");
  
        // Data
        sheet.getCellRange("A2").setValue("Harry");
        sheet.getCellRange("A3").setValue("Harry");
        sheet.getCellRange("A4").setValue("Harry");
        sheet.getCellRange("A5").setValue("Nicole");
        sheet.getCellRange("A6").setValue("Nicole");
        sheet.getCellRange("A7").setValue("Nicole");
        sheet.getCellRange("A8").setValue("Peter");
        sheet.getCellRange("A9").setValue("Peter");
        sheet.getCellRange("A10").setValue("Peter");
        sheet.getCellRange("A11").setValue("Lisa");
        sheet.getCellRange("A12").setValue("Lisa");
        sheet.getCellRange("A13").setValue("Lisa");
  
        sheet.getCellRange("B2").setValue("January");
        sheet.getCellRange("B3").setValue("February");
        sheet.getCellRange("B4").setValue("March");
        sheet.getCellRange("B5").setValue("January");
        sheet.getCellRange("B6").setValue("February");
        sheet.getCellRange("B7").setValue("March");
        sheet.getCellRange("B8").setValue("January");
        sheet.getCellRange("B9").setValue("February");
        sheet.getCellRange("B10").setValue("March");
        sheet.getCellRange("B11").setValue("January");
        sheet.getCellRange("B12").setValue("February");
        sheet.getCellRange("B13").setValue("March");
  
        sheet.getCellRange("C2").setValue("25");
        sheet.getCellRange("C3").setValue("22");
        sheet.getCellRange("C4").setValue("24");
        sheet.getCellRange("C5").setValue("24");
        sheet.getCellRange("C6").setValue("23");
        sheet.getCellRange("C7").setValue("24");
        sheet.getCellRange("C8").setValue("22");
        sheet.getCellRange("C9").setValue("15");
        sheet.getCellRange("C10").setValue("23");
        sheet.getCellRange("C11").setValue("25");
        sheet.getCellRange("C12").setValue("20");
        sheet.getCellRange("C13").setValue("18");
  
        // Add a PivotTable to the worksheet
        // Get Range of Table
        CellRange dataRange = sheet.getCellRange("A1:C13");
  
        PivotCache cache
            = workbook.getPivotCaches().add(dataRange);
        PivotTable pivotTable = sheet.getPivotTables().add(
            "Pivot Table", sheet.getCellRange("A16"),
            cache);
  
        // Drag the fields to the row area
        PivotField pivotField1 = null;
        if (pivotTable.getPivotFields().get("Student Name")
                instanceof PivotField) {
            pivotField1
                = (PivotField)pivotTable.getPivotFields()
                      .get("Student Name");
        }
        pivotField1.setAxis(AxisTypes.Row);
  
        PivotField pivotField2 = null;
        if (pivotTable.getPivotFields().get("Month")
                instanceof PivotField) {
            pivotField2
                = (PivotField)pivotTable.getPivotFields()
                      .get("Month");
        }
        pivotField2.setAxis(AxisTypes.Row);
  
        // Drag the field to the data area
        pivotTable.getDataFields().add(
            pivotTable.getPivotFields().get("Attendance"),
            "SUM of Attendance", SubtotalTypes.Sum);
  
        // Set PivotTable style
        pivotTable.setBuiltInStyle(
            PivotBuiltInStyles.PivotStyleMedium12);
  
        // Calculate data
        pivotTable.calculateData();
        
        // Set column width
        sheet.setColumnWidth(1, 14);
        sheet.setColumnWidth(2, 14);
  
        // Save the result file
        String workbookName = "Geeks_For_Geeks.xlsx";
        workbook.saveToFile(workbookName,
                            ExcelVersion.Version2013);
        System.out.println(workbookName
                           + " is written successfully");
    }
}

Salida: En la ventana de la consola

Cuando el programa se ejecuta con éxito.

Geeks_For_Geeks.xlsx is written successfully

Salida: Libro de trabajo (archivo de Excel)

Create Pivot Table in Excel using Java

Publicación traducida automáticamente

Artículo escrito por nandinigujral y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *