📜  如何使用Java在 Excel 中创建数据透视表?

📅  最后修改于: 2022-05-13 01:55:46.674000             🧑  作者: Mango

如何使用Java在 Excel 中创建数据透视表?

需要一个数据透视表来快速分析表中的数据,而无需付出任何努力(并且没有公式),有时并不是每个人都有时间查看表中的数据并查看正在发生的事情并使用它来构建美观的报告Excel 工作表中的大型数据集。让我们逐步讨论如何使用 Free Spire.XLS for Java API 在Java中的 Excel 文件中创建数据透视表。

分步实施

第1步:首先,在开始编写代码之前,需要将所需的依赖项添加到maven项目中,以包含Free Spire.XLS项目。

XML
 
  
    com.e-iceblue
    e-iceblue 
    http://repo.e-iceblue.com/nexus/content/groups/public/ 
    
 
  

   
    javax.xml.bind
    jaxb-api
    2.3.1 
    
    e-iceblue  
    spire.xls.free 
    3.9.1
  


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");
    }
}


步骤 2:创建工作簿

Workbook workbook = new Workbook();

第 3 步:创建工作表

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

第 4 步:将一些数据以表格形式添加到工作表中。

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

第 5 步:数据透视缓存是在您创建数据透视表时自动生成的。创建一个 PivotCache 对象并添加一个范围。

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

步骤 6:创建 PivotTable 对象以获取 PivotTable 并添加表名、Cell Range 从表开始的位置到 arg1、PivotCache arg2

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

第七步:创建数据透视字段,使用setAxis方法设置数据透视表布局后配置数据透视表的字段,然后选择类型。

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

第 8 步:将字段拖到数据区域

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

第 9 步:设置数据透视表样式

pivotTable.setBuiltInStyle(PivotBuiltInStyles.PivotStyleMedium12);

第 10 步:计算数据

pivotTable.calculateData();

第11步:用setColumnWidth方法设置列宽,首先有两个参数是int数据类型的columnIndex,double数据类型的宽度大小。

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

第 12 步:使用 saveToFile(String fileName, ExcelVersion version) 保存工作簿

workbook.saveToFile(workbookName, ExcelVersion.Version2013);

让我们编写Java程序在电子表格中创建数据透视表。

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");
    }
}

输出:在控制台窗口上

当程序成功执行时。

Geeks_For_Geeks.xlsx is written successfully

输出:工作簿(excel文件)

使用 Java 在 Excel 中创建数据透视表