Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POI Auto Filter

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.

like image 957
David Avatar asked Jun 24 '10 22:06

David


3 Answers

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)

like image 153
Victor Avatar answered Oct 10 '22 03:10

Victor


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));
like image 22
Anuja Avatar answered Oct 10 '22 04:10

Anuja


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

}
like image 38
Indranil Nag Avatar answered Oct 10 '22 02:10

Indranil Nag