在日常的数据分析开发中,我们经常需要对大量原始数据进行汇总、分类和统计。相比手动操作 excel,使用代码自动生成数据透视表(pivot table)不仅效率更高,还能很好地融入后端系统或数据处理流程。本文将介绍如何在 java 中创建 excel 数据透视表,并给出一个实用示例。
为什么使用代码创建数据透视表
在实际项目中,数据通常来源于数据库或接口。如果每次都手动打开 excel 再创建透视表,不仅耗时,还容易出错。通过 java 自动生成数据透视表,可以实现:
- 自动化报表生成
- 提高数据处理效率
- 保证结果一致性
- 便于集成到现有系统
准备工作
本文示例基于 spire.xls for java 实现。它提供了对 excel 文件的完整操作能力,包括创建工作簿、编辑数据、生成图表以及数据透视表等功能。
你可以通过 maven 引入依赖:
<dependency>
<groupid>e-iceblue</groupid>
<artifactid>spire.xls</artifactid>
<version>13.8.0</version>
</dependency>示例:创建数据透视表
下面通过一个简单示例,演示如何从已有数据创建数据透视表。
1. 准备数据
假设我们有如下结构的数据:
| region | product | sales |
|---|---|---|
| east | a | 100 |
| west | b | 200 |
| east | b | 150 |
| west | a | 120 |
2. java 实现代码
import com.spire.xls.*;
public class createpivottable {
public static void main(string[] args) {
workbook workbook = new workbook();
worksheet sheet = workbook.getworksheets().get(0);
// 写入数据
sheet.getcellrange("a1").settext("region");
sheet.getcellrange("b1").settext("product");
sheet.getcellrange("c1").settext("sales");
object[][] data = {
{"east", "a", 100}, {"west", "b", 200},
{"east", "b", 150}, {"west", "a", 120}
};
for (int i = 0; i < data.length; i++) {
sheet.getcellrange(i + 2, 1).settext((string)data[i][0]);
sheet.getcellrange(i + 2, 2).settext((string)data[i][1]);
sheet.getcellrange(i + 2, 3).setnumbervalue((integer)data[i][2]);
}
// 创建透视表
worksheet pivotsheet = workbook.getworksheets().add("pivottable");
cellrange datarange = sheet.getcellrange("a1:c" + (data.length + 1));
pivotcache cache = workbook.getpivotcaches().add(datarange);
pivottable pivottable = pivotsheet.getpivottables().add(
"pivottable", pivotsheet.getcellrange("a3"), cache
);
// 设置字段
pivottable.getpivotfields().get("region").setaxis(axistypes.row);
pivottable.getpivotfields().get("product").setaxis(axistypes.column);
pivottable.getdatafields().add(
pivottable.getpivotfields().get("sales"),
"total sales",
subtotaltypes.sum
);
workbook.savetofile("salespivottable.xlsx", excelversion.version2016);
system.out.println("完成!");
}
}
代码说明
上述代码主要分为几个关键步骤:
- 创建并填充原始数据
- 定义数据区域作为透视表的数据源
- 创建 pivotcache(用于缓存数据)
- 在新工作表中创建 pivottable
- 配置行、列和数据字段
- 设置汇总方式(如 sum)
理解这几个步骤之后,你就可以根据实际业务自由调整透视表结构,比如增加筛选字段、修改统计方式(平均值、计数等)等。
运行效果
程序运行后,会生成一个 excel 文件,并在新工作表中创建数据透视表,实现按 region 分组行、按 product 分组列,并对 sales 进行汇总统计。
方法补充
1.java 创建 excel 数据透视表
jar包准备:需要excel类库工具?free spire.xls for java,作者使用的是免费版。可去官网下载jar包后解压,将解压后lib文件夹下的spire.xls.jar手动导入到java程序;或者通过maven仓库下载导入。
java程序代码如下
import com.spire.xls.*;
public class createpivottable {
public static void main(string[] args) {
//加载excel测试文档
workbook wb = new workbook();
wb.loadfromfile("test.xlsx");
//获取第一个的工作表
worksheet sheet = wb.getworksheets().get(0);
//为需要汇总和分析的数据创建缓存
cellrange datarange = sheet.getcellrange("a1:d10");
pivotcache cache = wb.getpivotcaches().add(datarange);
//使用缓存创建数据透视表,并指定透视表的名称以及在工作表中的位置
pivottable pt = sheet.getpivottables().add("pivottable",sheet.getcellrange("a12"),cache);
//添加行字段1
pivotfield pf1 = null;
if (pt.getpivotfields().get("月份") instanceof pivotfield){
pf1 = (pivotfield) pt.getpivotfields().get("月份");
}
pf1.setaxis(axistypes.row);
//添加行字段2
pivotfield pf2 = null;
if (pt.getpivotfields().get("厂商") instanceof pivotfield){
pf2 = (pivotfield) pt.getpivotfields().get("厂商");
}
pf2.setaxis(axistypes.row);
//设置行字段的标题
pt.getoptions().setrowheadercaption("月份");
//添加列字段
pivotfield pf3 = null;
if (pt.getpivotfields().get("产品") instanceof pivotfield){
pf3 = (pivotfield) pt.getpivotfields().get("产品");
}
pf3.setaxis(axistypes.column);
//设置列字段标题
pt.getoptions().setcolumnheadercaption("产品");
//添加值字段
pt.getdatafields().add(pt.getpivotfields().get("总产量"),"求和项:总产量",subtotaltypes.sum);
//设置透视表样式
pt.setbuiltinstyle(pivotbuiltinstyles.pivotstyledark12);
//保存文档
wb.savetofile("数据透视表.xlsx", excelversion.version2013);
wb.dispose();
}
}2. java创建/刷新excel透视表
创建透视表
import com.spire.xls.*;
public class createpivottable {
public static void main(string[] args) {
//加载excel测试文档
workbook wb = new workbook();
wb.loadfromfile("test.xlsx");
//获取第一个的工作表
worksheet sheet = wb.getworksheets().get(0);
//为需要汇总和分析的数据创建缓存
cellrange datarange = sheet.getcellrange("a1:d10");
pivotcache cache = wb.getpivotcaches().add(datarange);
//使用缓存创建数据透视表,并指定透视表的名称以及在工作表中的位置
pivottable pt = sheet.getpivottables().add("pivottable",sheet.getcellrange("a12"),cache);
//添加行字段1
pivotfield pf1 = null;
if (pt.getpivotfields().get("月份") instanceof pivotfield){
pf1 = (pivotfield) pt.getpivotfields().get("月份");
}
pf1.setaxis(axistypes.row);
//添加行字段2
pivotfield pf2 = null;
if (pt.getpivotfields().get("厂商") instanceof pivotfield){
pf2 = (pivotfield) pt.getpivotfields().get("厂商");
}
pf2.setaxis(axistypes.row);
//设置行字段的标题
pt.getoptions().setrowheadercaption("月份");
//添加列字段
pivotfield pf3 = null;
if (pt.getpivotfields().get("产品") instanceof pivotfield){
pf3 = (pivotfield) pt.getpivotfields().get("产品");
}
pf3.setaxis(axistypes.column);
//设置列字段标题
pt.getoptions().setcolumnheadercaption("产品");
//添加值字段
pt.getdatafields().add(pt.getpivotfields().get("总产量"),"求和项:总产量",subtotaltypes.sum);
//设置透视表样式
pt.setbuiltinstyle(pivotbuiltinstyles.pivotstyledark12);
//保存文档
wb.savetofile("数据透视表.xlsx", excelversion.version2013);
wb.dispose();
}
}刷新透视表
import com.spire.xls.*;
public class refreshpivottable {
public static void main(string[] args) {
//创建实例,加载excel
workbook wb = new workbook();
wb.loadfromfile("数据透视表.xlsx");
//获取第一个工作表
worksheet sheet = wb.getworksheets().get(0);
//更改透视表的数据源数据
sheet.getcellrange("c2:c4").settext("产品a");
sheet.getcellrange("c5:c7").settext("产品b");
sheet.getcellrange("c8:c10").settext("产品c");
//获取透视表,刷新数据
pivottable pivottable = (pivottable) sheet.getpivottables().get(0);
pivottable.getcache().isrefreshonload();
//保存文档
wb.savetofile("刷新透视表.xlsx",fileformat.version2013);
}
}折叠、展开透视表中的行
import com.spire.xls.*;
import com.spire.xls.core.spreadsheet.pivottables.xlspivottable;
public class expandrows {
public static void main(string[] args) {
//加载包含透视表的excel
workbook wb = new workbook();
wb.loadfromfile("数据透视表.xlsx");
//获取数据透视表
xlspivottable pivottable = (xlspivottable) wb.getworksheets().get(0).getpivottables().get(0);
//计算数据
pivottable.calculatedata();
//展开”月份”字段下“2”的详细信息
pivotfield field = (pivotfield) pivottable.getpivotfields().get("月份");
field.hideitemdetail("2",false);
//折叠”月份”字段下“3”的详细信息
pivotfield field1 = (pivotfield) pivottable.getpivotfields().get("月份");
field1.hideitemdetail("3",true);
//保存并打开文档
wb.savetofile("展开、折叠行.xlsx", excelversion.version2013);
wb.dispose();
}
}小结
通过 java 自动创建数据透视表,可以显著提升数据处理效率,尤其适用于报表系统或批量数据分析场景。整个过程的核心在于数据源的定义以及透视表字段的配置。
在实际项目中,你可以将这一流程与数据库查询、定时任务等结合,实现完全自动化的数据分析输出。
到此这篇关于java创建excel数据透视表(pivot table)的完整实战教程的文章就介绍到这了,更多相关java创建excel数据透视表内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论