[英]Apache POI pivot table with horizontal columns
我喜欢这样的excel数据 当我想用下面的代码生成数据透视表时
XSSFSheet pivot = wb.createSheet("pivot");
AreaReference areaReference = new AreaReference("A2:D" + i, SpreadsheetVersion.EXCEL2007);
CellReference cellReference = new CellReference("A1");
XSSFPivotTable pivotTable = pivot.createPivotTable(areaReference, cellReference, sheet);
pivotTable.addRowLabel(1);
pivotTable.addRowLabel(2);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3);
我做错了什么?
顾名思义, addRowLabel
添加了行标签。 但是您希望data
表的列C
(2)成为列标签。 在apache poi
版本3.17之前,实现此目的的唯一方法是使用底层低层对象。 但这需要有关数据透视表内部的知识。
研究内部结构的最佳方法是使用Excel
的GUI创建一个具有数据透视表的*.xlsx
文件。 *.xlsx
文件不过是一个ZIP
存档。 因此,我们可以将其解压缩并进行查看。 在那里,我们将在/xl/worksheets
找到工作表的XML
文件,在/xl/pivotTables
数据透视表定义,在/xl/pivotCache
找到数据透视表缓存。 然后,根据此XML
我们可以使用org.openxmlformats.schemas.spreadsheetml.x2006.main.*
包的低级对象进行编程。
例:
码:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.SpreadsheetVersion;
import java.io.FileInputStream;
import java.io.FileOutputStream;
class PivotTableCreating {
public static void main(String[] args) throws Exception{
XSSFWorkbook wb = (XSSFWorkbook)WorkbookFactory.create(new FileInputStream("PivotExample.xlsx"));
XSSFSheet pivotSheet = wb.createSheet("pivot");
XSSFSheet dataSheet = wb.getSheet("data");
int lastRowNum = dataSheet.getLastRowNum();
XSSFPivotTable pivotTable = pivotSheet.createPivotTable(
new AreaReference(new CellReference("data!A1"), new CellReference("data!D" + (lastRowNum+1)),
SpreadsheetVersion.EXCEL2007),
new CellReference("A5"));
pivotTable.addRowLabel(1);
pivotTable.addRowLabel(2); //column C as a row label = RowField and AXIS_ROW
//do changing column C as a col label
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2)
.setAxis(org.openxmlformats.schemas.spreadsheetml.x2006.main.STAxis.AXIS_COL); //AXIS_COL
//remove column C from RowFields
pivotTable.getCTPivotTableDefinition().getRowFields().removeField(1);
pivotTable.getCTPivotTableDefinition().getRowFields().setCount(1);
//create ColFields for column C
pivotTable.getCTPivotTableDefinition().addNewColFields().addNewField().setX(2);
pivotTable.getCTPivotTableDefinition().getColFields().setCount(1);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 3);
wb.write(new FileOutputStream("PivotExampleNew.xlsx"));
wb.close();
}
}
结果:
如API
- XSSFPivotTable中所示,还有进一步的开发( addColLabel
)。 但是当前(2018年5月)最新的稳定版本apache poi
版本3.17没有提供此功能。
尝试在日期列上执行以下代码:
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(5).setAxis(STAxis.AXIS_COL)
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(5).addNewItems();
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(5).getItems().addNewItem()
.setT(STItemType.DEFAULT);
将5
替换为所需的数字(我假设2
)。 该代码旋转列的轴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.