当前位置: 首页 > 知识库问答 >
问题:

如何使用Apache POI从excel表访问透视表中的单元格值?

曹建明
2023-03-14

共有1个答案

华易安
2023-03-14

下面是一种自定义的方法来访问数据透视表头和数据,我不确定,但我不能找到一种方法来访问数据通过库,在网上搜索我读到的一些东西,说它还不支持。

让我们看看我做了什么:

输入文件:

        Map<String, Integer> map = new HashMap<String, Integer>() {
            {
                int index =1;
                for (char ch = 'A'; ch <= 'Z'; ++ch) {
                    put(String.valueOf(ch), index); 
                    index++;
                }
            }
    }; 
java.util.List<XSSFPivotTable> l = sh.getPivotTables();
<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>

看看ref=“f6:g7”,我就知道这个范围是什么了

 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));

完整的代码:

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();
    }
}

checkrightrowcol解释

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

        while (start!=end){
            if(n == start || n == end)
                return true;
            start++;
        }
        return false;
    }
 类似资料:
  • 我正在使用Poi.jar从excel表输入,想知道如何检查单元格是否为空。 现在我使用下面的代码。

  • 如何使用Java在透视表中设置标题。我必须使用apache POI在excel表中创建数据透视表。现在使用Java更改行和列标题标签。

  • 我正在组装一个简单的购物车系统,使用Laravel和Vue.js,来出售照片。每张照片都有不同的尺寸,每个尺寸的价格都不同。 我有以下表格: 我正在使用Vue.js对我的购物车控制器进行API调用,以操纵购物车。当用户单击“添加到篮子”按钮时,它会传递照片id和大小id。当然,我想从数据库而不是客户端获取所选项目的价格,以防止任何无礼行为,这自然意味着查询pivot表。 我的问题是,使用传递给控制

  • 我需要一个表格,第一行和第二行的单元格合并在一起。 大概是这样的: 桌子的图片(我不能张贴图片)http://i.stack.imgur.com/dAO6j.png 我一直在复习与本主题相关的所有问题,并找到了一些将网格跨度应用于单元的答案,但我找不到真正的解决方案。 以下是我从谷歌和本网站获得的示例代码: 我从这段代码中得到的信息如下: 我试图用

  • 有人知道从工作簿中的每个工作表中提取某个单元格值的命令吗?或者我可以写一个简单的宏?

  • 我有桌子: 用户 id 姓名 企业 id 姓名 公司/用户 company_id user_id 表有多对多的关系。 由于关系复杂,我不知道如何做这个限制,当用户可以看到由这个用户创建的公司。( 现在我有这个,但是用户可以看到任何公司 公司控制器: 所以提示我请如何让用户只能看到这个用户创建的公司。