如何在Java应用程序中创建Excel Pivot 表
mob 发布于 2021-03-12

数据透视表作为Excel中最强大的工具之一,具有计算、汇总和分析数据的能力,使我们能够更直观地看到数据的比较和趋势。此外,数据透视表还具有对数据进行排序和筛选的能力,它可以满足我们的日常业务报告要求。本文将介绍如何在Java应用程序中创建Excel数据透视表。


安装

方法一:你需要下载免费的用于Java的Spire.XLS并解压缩它。然后添加Spire.Xls.jar将文件作为依赖项添加到项目中。

方法2:如果您使用maven,那么可以通过将以下配置添加到pom.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>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>2.2.0</version>
    </dependency>
</dependencies>
创建Pivot Table代码

 import com.spire.xls.*;

public class CreatePivotTable {
    public static void main(String[] args)  {

        //Load a sample Excel workbook
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Sample.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        // Add a PivotTable to the worksheet
        CellRange dataRange = sheet.getCellRange("A1:D11");
        PivotCache cache = workbook.getPivotCaches().add(dataRange);
    PivotTable pt = sheet.getPivotTables().add("Pivot Table", sheet.getCellRange("F3"), cache);

        // Add the fields to the row area.
        PivotField pf=null;
        if (pt.getPivotFields().get("Country") instanceof PivotField){
            pf= (PivotField) pt.getPivotFields().get("Country");
        }
        pf.setAxis(AxisTypes.Row);

        PivotField pf2 =null;
        if (pt.getPivotFields().get("Product") instanceof PivotField){
            pf2= (PivotField) pt.getPivotFields().get("Product");
        }
        pf2.setAxis(AxisTypes.Row);

        // Add the field to the data area.
        pt.getDataFields().add(pt.getPivotFields().get("Amount"), "SUM of Amount", SubtotalTypes.Sum);

        //Set PivotTable style
        pt.setBuiltInStyle(PivotBuiltInStyles.PivotStyleMedium12);

        //Save the document
        workbook.saveToFile("CreatePivotTable.xlsx", ExcelVersion.Version2013);
    }
}
如图显示




mob
关注 私信
文章
61
关注
0
粉丝
0