2017-03-02 34 views
2

嗨,我使用自動篩選中的Excell過濾所有的列,它正在考慮所有的空行,而過濾(超出總沒有爲數據行的行)。但是,我想避免考慮空行,而我試圖過濾任何列。考慮刪除空白,而在POI過濾列中的Excell

我正在使用下面的代碼, sheet.setAutoFilter(CellRangeAddress.valueOf(「A8:L13」));

我目前得到這樣 I am currently getting like this

我需要這樣的 I need like this

+0

的'[](空白)'選項僅消失如果沒有在過濾器範圍空白單元格。所以'sheet.setAutoFilter(CellRangeAddress.valueOf(「A8:L13」));'在你的特殊情況下。 –

+0

沒有42是不恆定的,這是動態的。在這種情況下,它必須是13 ..但問題是它正在考慮所有的空白行(行數超過總行數),而過濾。 –

+0

然後不要使用常量,只要添加一行,使用'Sheet.getLastRow()'重置自動過濾器。 – jmarkmurphy

回答

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