1

How to access cell value from pivot table from excel sheet using Apache POI? I tried using XSSFPivotTable.getPivotTables, but not able to access cell value. Book1.xlsx is the excel workbook which has a pivot table on sheet Sheet1.

FileInoutStream input = new FileInputStream(new File(Book1.xlsx)); XSSFWorkbook wb = new XSSFWorkbook(input); XSSFSheet sh = wb.getSheet("Sheet1"); XSSFPivotTable pt = sh.getPivotTables().get(0);

Not able to access the cells in pt pivot table ahead of this.

4
  • 2
    Hi. Please add a MVCE (stackoverflow.com/help/mcve) so we can have a better look at what youre trying to do and where the problem could be. Commented Aug 29, 2017 at 14:14
  • @FabianSchöner Added MCVE. Commented Sep 1, 2017 at 8:39
  • Did you got the answer? Commented Sep 4, 2017 at 7:00
  • Did you got solution ? Commented Nov 11, 2019 at 6:22

1 Answer 1

1

Below a custom way to access to pivot table header and data , im not sure but i couldnt find a way to access to the data via library , searching on line i read something about, which says it is not supported yet .

Lets see what i did :

Input file :

enter image description here

Tranform letters in numbers for columns:

        Map<String, Integer> map = new HashMap<String, Integer>() {
            {
                int index =1;
                for (char ch = 'A'; ch <= 'Z'; ++ch) {
                    put(String.valueOf(ch), index); 
                    index++;
                }
            }
    }; 

Getting table object

java.util.List<XSSFPivotTable> l = sh.getPivotTables();

Below the code which will make a trick for the result

XML Debug view :

<xml-fragment name="PivotTable7" cacheId="24" applyNumberFormats="0" applyBorderFormats="0" applyFontFormats="0" applyPatternFormats="0" applyAlignmentFormats="0" applyWidthHeightFormats="1" dataCaption="Values" updatedVersion="6" minRefreshableVersion="3" useAutoFormatting="1" itemPrintTitles="1" createdVersion="6" indent="0" outline="1" outlineData="1" multipleFieldFilters="0" xmlns:main="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  <main:location ref="F6:G7" firstHeaderRow="0" firstDataRow="1" firstDataCol="0"/>
  <main:pivotFields count="2">
    <main:pivotField dataField="1" subtotalTop="0" showAll="0">
      <main:items count="2">
        <main:item x="0"/>
        <main:item t="default"/>
      </main:items>
    </main:pivotField>
    <main:pivotField dataField="1" subtotalTop="0" showAll="0"/>
  </main:pivotFields>
  <main:rowItems count="1">
    <main:i/>
  </main:rowItems>
  <main:colFields count="1">
    <main:field x="-2"/>
  </main:colFields>
  <main:colItems count="2">
    <main:i>
      <main:x/>
    </main:i>
    <main:i i="1">
      <main:x v="1"/>
    </main:i>
  </main:colItems>
  <main:dataFields count="2">
    <main:dataField name="A" fld="0" baseField="0" baseItem="1"/>
    <main:dataField name="B" fld="1" baseField="0" baseItem="1"/>
  </main:dataFields>
  <main:pivotTableStyleInfo name="PivotStyleLight16" showRowHeaders="1" showColHeaders="1" showRowStripes="0" showColStripes="0" showLastColumn="1"/>
  <main:extLst>
    <main:ext uri="{962EF5D1-5CA2-4c93-8EF4-DBF5C05439D2}" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main">
      <x14:pivotTableDefinition hideValuesRow="1" xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main"/>
    </main:ext>
    <main:ext uri="{747A6164-185A-40DC-8AA5-F01512510D54}" xmlns:xpdl="http://schemas.microsoft.com/office/spreadsheetml/2016/pivotdefaultlayout">
      <xpdl:pivotTableDefinition16 SubtotalsOnTopDefault="0"/>
    </main:ext>
  </main:extLst>
</xml-fragment>

Looking at ref="F6:G7" i know the range which will make the trick

 String range = l.get(0).getCTPivotTableDefinition().getLocation().getRef(); //F6:G7 rows/cols reference - case of our sheet

            //determinate range of table
            int firstcol = map.get(range.substring(0, 1));
            int firstrow = Integer.parseInt(range.substring(1, 2));
            int lastcol = map.get(range.substring(3, 4));
            int lastrow = Integer.parseInt(range.substring(4, 5));

The complete code :

public static void main(String[] args) {

        //tranform letters in numbers for columns
        Map<String, Integer> map = new HashMap<String, Integer>() {
            {
                int index =1;
                for (char ch = 'A'; ch <= 'Z'; ++ch) {
                    put(String.valueOf(ch), index); 
                    index++;
                }
            }
    };
    try {
        FileInputStream input = new FileInputStream(new File("C:\\Desktop\\ook.xlsx"));

        XSSFWorkbook wb = new XSSFWorkbook(input);
        XSSFSheet sh = wb.getSheet("Sheet1");

        Iterator<Row> rowIterator = sh.iterator();
        ArrayList columndata = new ArrayList<>();

        java.util.List<XSSFPivotTable> l = sh.getPivotTables();

        String range = l.get(0).getCTPivotTableDefinition().getLocation().getRef(); //F6:G7 rows/cols reference - case of our sheet

        //determinate range of table
        int firstcol = map.get(range.substring(0, 1));
        int firstrow = Integer.parseInt(range.substring(1, 2));
        int lastcol = map.get(range.substring(3, 4));
        int lastrow = Integer.parseInt(range.substring(4, 5));

while (rowIterator.hasNext()) {

    Row row = rowIterator.next();
    if(checkrightrowcol(row.getRowNum()+1, firstrow, lastrow)){
    Iterator<Cell> cellIterator = row.cellIterator();
    while (cellIterator.hasNext()) {
        Cell cell = cellIterator.next();

        if(checkrightrowcol(cell.getColumnIndex()+1,firstcol,lastcol)){    

           switch(cell.getCellType()){
            case Cell.CELL_TYPE_NUMERIC: // numeric value 
                System.out.println(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING: // String Value 
                System.out.println(cell.getStringCellValue());
                break;

                //..add more 
                }
            }
           }
        }
    }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

Explanation of checkrightrowcol

public static boolean checkrightrowcol(int n , int start, int end){

        while (start!=end){
            if(n == start || n == end)
                return true;
            start++;
        }
        return false;
    }

If it returns true im in the table data , in the main i use "+1" because rows and columns indexes start from "0"

Result :

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

I tried the above code, but facing a weird issue. Able to get correct range say K6:N21 if the pivot is created manual in excel, but if pivot is created programmatically then getting range as K6:L7. And just for records, the pivot table is created correct with program.
I see man , im not sure , but it could be a limit of the library

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.