使用apache poi库给excel文件添加筛选功能,可以遵循以下步骤:
1. 创建workbook对象
workbook wb = new hssfworkbook(); // 或 new xssfworkbook()
2. 创建sheet对象
sheet sheet = wb.createsheet();
3. 指定筛选区域
立即学习“Java免费学习笔记(深入)”;
sheet.setautofilter(cellrangeaddress.valueof("c5:f200")); // 区域:c列5行~f列200行
4. 保存工作簿
outputstream fileout = files.newoutputstream(paths.get("workbook.xls")); wb.write(fileout);
示例代码:
try ( Workbook wb = new HSSFWorkbook(); // 或 new XSSFWorkbook(); OutputStream fileOut = Files.newOutputStream(Paths.get("workbook.xls")) ) { Sheet sheet = wb.createSheet(); // 指定区域设置自动筛选 sheet.setAutoFilter(CellRangeAddress.valueOf("C5:F200")); // 区域:C列5行~F列200行 wb.write(fileOut); } catch (IOException e) { throw new RuntimeException(e); }
运行效果: