POI Auto Filter
Asked Answered
C

7

14

How do I use Apache POI to pre-define an auto-filter region in an Excel 2007 document?

A small code example or link would be nice.

Carloscarlota answered 24/6, 2010 at 22:1 Comment(0)
L
24

Save the first and the last cell from the filter area, and execute:

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

For example, from the sheet below.

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

fist cell will be the header above the first + (2,1) cell. The the last will be the last + cell (5,3)

Lori answered 4/12, 2012 at 16:4 Comment(2)
@Lori don't you mean the first cell will be (2,0) and the last will be (4,3)? Therefore you'd call sheet.setAutoFilter(new CellRangeAddress(0, 3, 2, 4));Extrajudicial
I needed to replace getRow and getCol with getRowIndex and getColumnIndex.Anubis
Y
7

I found it difficult to get the CellRange since my columns and row values were both variable. So I used this trick.

Initialize a lastCellReference variable to A1 which is row1, column1 cell

String lastCellReference = "A1";

Everytime you create a cell update the lastCellReference to maintain latest value

cell = row.createCell((short) columnCount);
cell.setCellValue(rs.getInt(i)); 
lastCellReference=cell.getReference();

A1 will always be first cell and then the lastCellReference

 sheet1.setAutoFilter(CellRangeAddress.valueOf("A1:"+ lastCellReference));
Yesman answered 15/1, 2016 at 11:6 Comment(0)
G
5
//include poi-3.7.jar,ojdbc.jar in classpath
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;

public class ExcelCreator{
public static void createExcel(String anySql,OutputStream out) throws Exception{
Connection conn=getOracleConnection();
String userSql1="select * from tab";
String userSql2="select * from tab";
    String[] sqls={userSql1,userSql2,anySql};
    String[] workSheetNames={"User","Manager","Any"};
       HSSFWorkbook wb = new HSSFWorkbook();
       CellStyle style1 = wb.createCellStyle();
       CellStyle style2 = wb.createCellStyle();
       for(int i=0;i<lt;sqls.length;i++){
           if(sqls[i]==null||sqls[i].length()==0){
               continue;
           }
        HSSFSheet sheet = wb.createSheet(workSheetNames[i]);


           Statement st = conn.createStatement();
          System.out.println("--------------------------");
          System.out.println(sqls[i]);
           ResultSet    rs = st.executeQuery(sqls[i]);
           ResultSetMetaData rsMetaData = rs.getMetaData();
           int numberOfColumns = rsMetaData.getColumnCount();
           int rowCounter=0;
           HSSFRow rowHeader     = sheet.createRow(rowCounter);
            for(int columnCounter=0; columnCounter<lt;numberOfColumns;columnCounter++){

                rowHeader.createCell(columnCounter).setCellValue(rsMetaData.getColumnName(columnCounter+1));
                    setFilledColorStyle(rowHeader.getCell(columnCounter),style2);
            }
            sheet.setAutoFilter(org.apache.poi.ss.util.CellRangeAddress.valueOf("A1:"+ (Character.toString((char)( 65+numberOfColumns-1)))+"1")); 

            rowCounter++;
            while(rs.next()) {
                // Create a row and put some cells in it. Rows are 0 based.
                HSSFRow row     = sheet.createRow(rowCounter);
                for(int columnCounter=0; columnCounter<lt;numberOfColumns;columnCounter++){
                        row.createCell(columnCounter).setCellValue(rs.getString(columnCounter+1));
                        setThinBorderStyle(row.getCell(columnCounter),style1);

                }
                rowCounter++;
            }
            rs.close();
            st.close();
           }        


        // Write the output 

        wb.write(out);
        out.close();
        conn.close();
        System.out.println("Created Successfully");
}

public static void main(String[] args) throws Exception{
     OutputStream out = new FileOutputStream("c:/admin.xls");
     createExcel(" select * from tab", out);
}
public static Connection getOracleConnection() throws Exception {
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:XE";


  String username = "system";
  String password = "password";




    Class.forName(driver); // load Oracle driver
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
  }
//This method set the thin border style 
private static void setThinBorderStyle(Cell cell, CellStyle style) {
    style.setBorderBottom(CellStyle.BORDER_THIN);
    style.setBottomBorderColor(IndexedColors.RED.getIndex());
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setLeftBorderColor(IndexedColors.RED.getIndex());
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setRightBorderColor(IndexedColors.RED.getIndex());
    style.setBorderTop(CellStyle.BORDER_THIN);
    style.setTopBorderColor(IndexedColors.RED.getIndex());
    cell.setCellStyle(style);
} 
//This method set the dashed border style 
private static void setDashedBorderStyle(Cell cell, CellStyle style) {
    style.setBorderBottom(CellStyle.BORDER_DASHED);
    style.setBottomBorderColor(IndexedColors.GREEN.getIndex());
    style.setBorderLeft(CellStyle.BORDER_DASHED);
    style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
    style.setBorderRight(CellStyle.BORDER_DASHED);
    style.setRightBorderColor(IndexedColors.GREEN.getIndex());
    style.setBorderTop(CellStyle.BORDER_DASHED);
    style.setTopBorderColor(IndexedColors.GREEN.getIndex());
    cell.setCellStyle(style);
} // This method set the dotted border style 
private static void setFilledColorStyle(Cell cell, CellStyle style) {
    // style.setFillBackgroundColor(new HSSFColor.YELLOW().getIndex());
     style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());

     style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND );
//   style.setBorderLeft(CellStyle.BORDER_DOTTED);
//   style.setLeftBorderColor(IndexedColors.BLUE.getIndex());
//   style.setBorderRight(CellStyle.BORDER_DOTTED);
//   style.setRightBorderColor(IndexedColors.BLUE.getIndex());
//   style.setBorderTop(CellStyle.BORDER_DOTTED);
//   style.setTopBorderColor(IndexedColors.BLUE.getIndex());
     cell.setCellStyle(style); 
     }

}
Genip answered 7/3, 2012 at 17:6 Comment(1)
Thank you for sharing. You can also add "import org.apache.poi.ss.util.CellRangeAddress" to the import section and get rid of "org.apache.poi.ss.util." inside "sheet.setAutoFilter" line.Glue
G
4
    sets Auto filter

    sheet.setAutoFilter(CellRangeAddress.valueOf("A1:N1")); 
Genic answered 21/8, 2012 at 11:53 Comment(0)
R
2

This functionality becomes avaliable since 3.7-beta3-20100811 version of apache POI

Residentiary answered 3/11, 2010 at 10:15 Comment(0)
C
1

Answer: It's not possible (yet).

https://issues.apache.org/bugzilla/show_bug.cgi?id=35125

Carloscarlota answered 25/6, 2010 at 14:56 Comment(0)
S
0

Set autoFilters with first row but last column once your row exists and populated

            final XSSFRow firstRow = sheet.getRow(0);
            final short lastCellNum = firstRow.getLastCellNum();
            final XSSFCell lastCell = firstRow.getCell(lastCellNum - 1);
            final String lastCellReference = lastCell.getReference();
            sheet.setAutoFilter(CellRangeAddress.valueOf("A1:" + lastCellReference));
Supertax answered 5/10, 2022 at 13:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.