Setting filter on headers of an Excel sheet via POI

前端 未结 5 795
一个人的身影
一个人的身影 2021-01-30 21:06

I generate a sheet, pretty bog standard headers and columns of data.

I want to turn on the \"Filter\" function for the sheet, so the user can easily sort and filter the

5条回答
  •  执笔经年
    2021-01-30 21:34

    If you also want to set a filter programmatically, you could use the following:

    void setAutoFilter(final XSSFSheet sheet, final int column, final String value) {
        sheet.setAutoFilter(CellRangeAddress.valueOf("A1:Z1"));
    
        final CTAutoFilter sheetFilter = sheet.getCTWorksheet().getAutoFilter();
        final CTFilterColumn filterColumn = sheetFilter.addNewFilterColumn();
        filterColumn.setColId(column);
        final CTFilter filter = filterColumn.addNewFilters().insertNewFilter(0);
        filter.setVal(value);
    
        // We have to apply the filter ourselves by hiding the rows: 
        for (final Row row : sheet) {
            for (final Cell c : row) {
                if (c.getColumnIndex() == column && !c.getStringCellValue().equals(value)) {
                    final XSSFRow r1 = (XSSFRow) c.getRow();
                    if (r1.getRowNum() != 0) { // skip header
                        r1.getCTRow().setHidden(true);
                    }
                }
            }
        }
    }
    

    Relevant Gradle dependencies:

        // https://mvnrepository.com/artifact/org.apache.poi/poi
    compile group: 'org.apache.poi', name: 'poi', version: '3.9'
    
    // https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml
    compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.9'
    
    // https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas
    compile group: 'org.apache.poi', name: 'poi-ooxml-schemas', version: '3.9'
    
    // https://mvnrepository.com/artifact/org.apache.poi/ooxml-schemas
    compile group: 'org.apache.poi', name: 'ooxml-schemas', version: '1.3'
    

提交回复
热议问题