POI创建透视表

添加poi版本依赖

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>

示例代码

    /**
     * poi 透视表的创建
     * @param filePath 原始数据文件路径
     * @param outFilePath 输出文件路径
     */
    public static void createPivotTable(String filePath,String outFilePath){
        File file = new File(filePath);
        // 创建XSSFWorkbook
        XSSFWorkbook workbook;
        try (FileInputStream fileInputStream = new FileInputStream(file);){
             workbook = XSSFWorkbookFactory.createWorkbook(fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        // 获取透视表数据源
        XSSFSheet buyerReview = workbook.getSheet("Review");
        // 创建一个新的sheet也。用于存放透视表
        XSSFSheet overallReport = workbook.createSheet("pivot sheet");
        // 获取透视表的最后一行行号
        int lastRowNum = buyerReview.getLastRowNum();
        // 透视表数据源数据区域
        AreaReference area = new AreaReference("A1:K" + lastRowNum, SpreadsheetVersion.EXCEL2007);
        // 透视表显示起始位置
        CellReference position = new CellReference("A2");

        XSSFPivotTable pivotTable = overallReport.createPivotTable(area, position, buyerReview);
        // 添加行标签
        pivotTable.addRowLabel(0);
        pivotTable.addRowLabel(8);

        // 添加列标签,列标签会横向展示
        pivotTable.addColLabel(10);
        // 添加行数据统计函数
        pivotTable.addColumnLabel(DataConsolidateFunction.COUNT,10,"FieldName");

        // 写出到文件
        try(FileOutputStream fileOutputStream = new FileOutputStream(new File(outFilePath))){
            workbook.write(fileOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

不知是POI的bug还是用法问题,如果同时使用了使用了列标签和列的函数,会导致MircoSoft Excel打不开透视表。而WPS和LibreOffice却可以打开,用LibreOffice另存为Excel格式后就可以使用MircoSoft正常打开。目前这个问题正在研究中的。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容