最近有个需求是关于导出Excel数据透视表的,先写了一个简单的demo,有不足之处还请大佬讲解
1.首先,我引入的poi是3.15版本的
pom文件:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
2.在磁盘中,创建一个模板
模板位置自定义,然后在模板中添加数据(用这些数据生成数据透视表)
注意:这里数据的位置区域是A1:E4,下面在代码中用到
逻辑代码:
public class PoiPivotal {
public static void main(String[] args) throws IOException {
//创建一个模板文件,里面自己手动填入数据
FileInputStream file = new FileInputStream(new File("D:/company/a.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
//获取sheet页数据行数
int num = sheet.getLastRowNum();
//手动填充数据的区域
AreaReference a=new AreaReference("A1:E4");
//数据透视表生成为位置
CellReference b=new CellReference("I5");
//生成数据透视图
XSSFPivotTable pivotTable = sheet.createPivotTable(a,b);
//添加行标签
pivotTable.addRowLabel(0);
//添加列数据
//pivotTable.addDataColumn(0, true);
//pivotTable.addDataColumn(1, true);
//指定生成文件位置
FileOutputStream output_file = new FileOutputStream(new File("D:/company/"+"POI_XLS_Pivot_Example.xlsx"));
workbook.write(output_file);//write excel document to output stream
output_file.close(); //close the file
}
}
代码中有详细的注释,但是我在用 pivotTable.addDataColumn(0, true) 添加列数据时,生成的文件打不开,我也不知道为什么,还请大佬指教!!!!
最后运行,生成文件
打开文件后,发现数据透视表默认没有展示数据列,因为代码中 pivotTable.addDataColumn(0, true) 的问题。需要手动调整数据透视表
在右侧栏,把这些都勾选上
一个简单的数据透视表,就这样磕磕绊绊的完成了。
最后还请大佬多多指教代码实现中存在的问题!!