繁体   English   中英

XSSF(Apache POI)-从数据透视表中的单列值添加多列标签

[英]XSSF(Apache POI) - Adding multiple column label from single column value in pivot table

我目前正在使用Apache POI 3.12添加数据透视表。 这是我的sample.xlsx文件:

在此处输入图片说明

现在,我使用以下代码为上述数据创建数据透视表。

    File excel = new File("sample.xlsx"); 
    FileInputStream fis = new FileInputStream(excel); 
    XSSFWorkbook wb = new XSSFWorkbook(fis); 
    XSSFSheet sheet = wb.getSheetAt(0); 
    XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference("A3:C7"), new CellReference("E3"));
    pivotTable.addRowLabel(0);
    pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
    pivotTable.addDataColumn(1, true);
    pivotTable.addReportFilter(2);
    FileOutputStream fileOut = new FileOutputStream("output.xlsx");
    wb.write(fileOut);
    fileOut.close();
    wb.close();

我的output.xlsx文件具有以下数据透视表:

在此处输入图片说明

当我要在excel中编辑数据透视表时,会在页面字段而不是列字段中添加year列。 实际上,我需要以下结果:

在此处输入图片说明

我无法从单列值添加多列标签。 请你帮助我好吗? 提前致谢

XSSFPivotTable类处于@Beta状态。 因此,只有使用底层的低层对象才有可能。

XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("sample.xlsx")); 
XSSFSheet sheet = wb.getSheetAt(0);

//the following creates a Pivot Table with 3 PivotFields (0 to 2) (3 Columns A3:C7); all dataField="false" at first 
XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference(new CellReference("A3"), new CellReference("C7")), new CellReference("E3"));

//the following makes PivotFields(0) an Axis-Field AXIS_ROW with 5 Items (5 Rows A3:C7). Why one Item for each row? I don't know.
//and it adds a new RowField for this
pivotTable.addRowLabel(0);

//the following makes PivotFields(1) a DataField and creates a DataColumn for this
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
//pivotTable.addDataColumn(2, false); //not neccessary since addColumnLabel already adds a DataColumn

//now PivotFields(2) needs to be an Axis-Field AXIS_COL
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).setAxis(
  org.openxmlformats.schemas.spreadsheetml.x2006.main.STAxis.AXIS_COL);

//PivotFields(2) needs to have at least one Item  
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).addNewItems();
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(2).getItems().addNewItem().setT(
  org.openxmlformats.schemas.spreadsheetml.x2006.main.STItemType.DEFAULT);

//new ColField needs to be added
pivotTable.getCTPivotTableDefinition().addNewColFields().addNewField().setX(2);

//pivotTable.addReportFilter(2);
FileOutputStream fileOut = new FileOutputStream("output.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();

pivotTable.addDataColumn(1, true); 不需要,因为addColumnLabel已经添加了一个DataColumn

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM