我有这样的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
添加行标签。但您希望数据
表的C
(2)列成为列标签。在 apache poi
版本 3.17 之前,实现此目的的唯一方法是使用底层低级对象。但这需要了解数据透视表的内部结构。
研究内部结构的最佳方法是使用 Excel
的 GUI 创建一个具有数据透视表的 *.xlsx
文件。这个*.xlsx
文件只不过是一个ZIP
存档。所以我们可以将其解压并查看。在那里,我们将在 /xl/worksheets
中找到工作表的 XML
文件,在 /xl/pivotTables
中找到数据透视表定义,在 /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不提供此功能。
关于java - 具有水平列的 Apache POI 数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49980485/