加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 使用Apache POI将列标签插入数据透视表?

发布时间:2020-12-14 05:48:03 所属栏目:Java 来源:网络整理
导读:我使用Apache POI 3.11创建了一个数据透视表.像这样: FileInputStream file = new FileInputStream(new File(path+fname));XSSFWorkbook workbook = new XSSFWorkbook(file);XSSFSheet sheet = workbook.getSheetAt(0);//area of pivot dataAreaReference a
我使用Apache POI 3.11创建了一个数据透视表.像这样:
FileInputStream file = new FileInputStream(new File(path+fname));

XSSFWorkbook workbook = new  XSSFWorkbook(file);

XSSFSheet sheet = workbook.getSheetAt(0);
//area of pivot data
AreaReference a=new AreaReference("A1:J4");

CellReference b=new CellReference("N5");    
XSSFPivotTable pivotTable = sheet.createPivotTable(a,b);

//insert row
pivotTable.addRowLabel(3);
pivotTable.addRowLabel(6);

//insert column
pivotTable.addColumnLabel(DataConsolidateFunction.COUNT,5);

//export
FileOutputStream output_file = 
   new FileOutputStream(new File(path+"POI_XLS_Pivot_Example.xlsx")); 
workbook.write(output_file);//write excel document to output stream
output_file.close(); //close the file

生成报告后,它会正确显示行.但它没有显示列标签:

我想在我的数据透视表中显示列标签,如下所示:

img http://www.pivot-table.com/wp-content/uploads/2010/12/calculateditem04.png

有谁知道这个问题的解决方案?

谢谢.

解决方法

以下方法(稍微修改过的XSSFPivotTable.addRowLabel版本)添加了“普通”透视列标签:
public static void addColLabel(XSSFPivotTable pivotTable,int columnIndex) {
    AreaReference pivotArea = new AreaReference(pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition()
            .getCacheSource().getWorksheetSource().getRef());
    int lastRowIndex = pivotArea.getLastCell().getRow() - pivotArea.getFirstCell().getRow();
    int lastColIndex = pivotArea.getLastCell().getCol() - pivotArea.getFirstCell().getCol();

    if (columnIndex > lastColIndex) {
        throw new IndexOutOfBoundsException();
    }
    CTPivotFields pivotFields = pivotTable.getCTPivotTableDefinition().getPivotFields();

    CTPivotField pivotField = CTPivotField.Factory.newInstance();
    CTItems items = pivotField.addNewItems();

    pivotField.setAxis(STAxis.AXIS_COL);
    pivotField.setShowAll(false);
    for (int i = 0; i <= lastRowIndex; i++) {
        items.addNewItem().setT(STItemType.DEFAULT);
    }
    items.setCount(items.sizeOfItemArray());
    pivotFields.setPivotFieldArray(columnIndex,pivotField);

    CTColFields rowFields;
    if (pivotTable.getCTPivotTableDefinition().getColFields() != null) {
        rowFields = pivotTable.getCTPivotTableDefinition().getColFields();
    } else {
        rowFields = pivotTable.getCTPivotTableDefinition().addNewColFields();
    }

    rowFields.addNewField().setX(columnIndex);
    rowFields.setCount(rowFields.sizeOfFieldArray());
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读