通过POI在Excel工作表的标题上设置过滤器

问题描述 投票:29回答:5

我生成一个工作表,非常沼泽的标准标题和数据列。

我想打开工作表的“过滤器”功能,这样用户就可以轻松地对数据进行排序和过滤。

我可以这样使用POI吗?

excel apache-poi autofilter
5个回答
54
投票

保存过滤区域中的第一个和最后一个单元格,然后执行:

sheet.setAutoFilter(new CellRangeAddress(firstCell.getRow(), lastCell.getRow(), firstCell.getCol(), lastCell.getCol()));

例如,从下面的表格中。

>x         (x, y)
  0123456  
0|--hhh--|   h = header
1|--+++--|   + = values
2|--+++--|   - = empty fields
3|--+++--|
4|-------|

第一个单元格将是第一个+(2,1)单元格上方的标题。最后一个将是最后一个+单元格(5,3)


3
投票

在标题上添加过滤器的最简单方法:

sheet.setAutoFilter(new CellRangeAddress(0, 0, 0, numColumns));
sheet.createFreezePane(0, 1);

0
投票

如果您还想以编程方式设置过滤器,则可以使用以下命令:

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

相关的Gradle依赖项:

    // 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'

0
投票

我想出了如何用NPOI做到这一点。 您将CT_AutoFilter添加到CT_Table。

我猜它对于POI和NPOI的工作方式相同。

    cttable.autoFilter = new CT_AutoFilter();
    cttable.autoFilter.@ref = "A1:C5";   // value is data and includes header.

0
投票

使用sheet.setAutoFilter(CellRangeAddress.valueOf("B1:H1"));

我们只需要指定表格数据的标题单元格。在我的示例中,标题从单元格B1开始,到单元格H1结束。 Excel将自动查找其下方的数据并在过滤器选项中显示。

© www.soinside.com 2019 - 2024. All rights reserved.