在POI中过滤Excell中的列时删除考虑空白

时间:2017-03-02 10:43:11

标签: java apache-poi

您好我正在使用autoFilter过滤Excell中的所有列,它会在过滤时考虑所有空白行(超出具有数据的行的总数)。但是,我想在尝试过滤任何列时避免考虑空行。

我使用下面的代码, sheet.setAutoFilter(CellRangeAddress.valueOf(" A8:L13&#34));

我目前正是这样的 I am currently getting like this

我需要这样的 I need like this

1 个答案:

答案 0 :(得分:1)

如果过滤器范围中没有空白单元格,则自动过滤[ ] (Blanks)选项仅会消失。因此,我们只需将AutoFilter单元格范围设置为使用范围。

示例:

import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;

import java.util.Random;
import java.io.*;

class AutoFilterTest {

 private static void setCellData(Sheet sheet) {

  Row row = sheet.createRow(0);
  Cell cell = row.createCell(0);
  cell.setCellValue("Name");
  cell = row.createCell(1);
  cell.setCellValue("Value1");
  cell = row.createCell(2);
  cell.setCellValue("Value2");
  cell = row.createCell(3);
  cell.setCellValue("City");

  Random rnd = new Random();

  for (int r = 1; r < 10 + rnd.nextInt(100); r++) {
   row = sheet.createRow(r);
   cell = row.createCell(0);
   cell.setCellValue("Name " + ((r-1) % 4 + 1));
   cell = row.createCell(1);
   cell.setCellValue(r * rnd.nextDouble());
   cell = row.createCell(2);
   cell.setCellValue(r * rnd.nextDouble());
   cell = row.createCell(3);
   cell.setCellValue("City " + ((r-1) % 3 + 1));  
  }

 }

 public static void main(String[] args) {
  try {
   XSSFWorkbook wb = new XSSFWorkbook();
   XSSFSheet sheet = wb.createSheet();

   //create random rows of data
   setCellData(sheet);

   for (int c = 0; c < 4; c++) sheet.autoSizeColumn(c);

   int lastRow = sheet.getLastRowNum();
   sheet.setAutoFilter(new CellRangeAddress(0, lastRow, 0, 3));

   wb.write(new FileOutputStream("AutoFilterTest.xlsx"));
   wb.close();
  } catch (Exception e) {
    e.printStackTrace();
  }
 }
}