我生成了一个带有标准标题和数据列的表格。
我想为该表格开启“筛选”功能,以便用户可以轻松地对数据进行排序和筛选。
我能否使用POI来实现这一点?
我生成了一个带有标准标题和数据列的表格。
我想为该表格开启“筛选”功能,以便用户可以轻松地对数据进行排序和筛选。
我能否使用POI来实现这一点?
保存筛选区域的第一个和最后一个单元格,并执行:
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)。
new CellRangeAddress( firstCell.getRowIndex(), lastCell.getRowIndex(), firstCell.getColumnIndex(), lastCell.getColumnIndex() )
。现在getRow()
返回一个行对象而不是索引,getCol()
已不存在。 - Matt Penningtonsheet.setAutoFilter(new CellRangeAddress(0, 0, 0, numColumns));
sheet.createFreezePane(0, 1);
numColumns - 1
(否则最后会多出一个过滤器列)。 - Priidu NeemreCellRangeAddress
的构造函数是从零开始索引和包含边界的。因此,如果您正在基于某些内容计算 numColumns
,则需要考虑这一点。 - Priidu NeemrelastIndex
比numColumns
更合适(或者我会使用numColumns - 1
)。 - Juliovoid 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'
cttable.autoFilter = new CT_AutoFilter();
cttable.autoFilter.@ref = "A1:C5"; // value is data and includes header.
SetAutoFilter
会向工作表添加一些数据,但在我的情况下,它还会导致Excel抱怨并修复文档,将表格删除。 - Yennefer使用 sheet.setAutoFilter(CellRangeAddress.valueOf("B1:H1"));
我们需要指定表格数据的表头单元格。在我的示例中,表头从单元格B1开始,结束于单元格H1。
Excel会自动查找下面的数据并在筛选选项中显示它。