Some Useful Method When Working With Apache POI (Excel)

  1. How to add color on background/foreground cell
    public void doSample(){
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheetLapTrx = workbook.createSheet("Sample Sheet");
        row = sheetLapTrx.createRow(0);
        cell = row.createCell((short) 0);
    
        XSSFCellStyle style = (XSSFCellStyle)workbook.createCellStyle();
    
        XSSFColor color = new XSSFColor(Color.GREEN);
        style.setFillForegroundColor(color);
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);	
    
        cell.setCellStyle(style);
    }
    
  2. How to merge cell
    public void doSample(){
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheetLapTrx = workbook.createSheet("Sample Sheet");
        row = sheetLapTrx.createRow(0);
        cell = row.createCell((short) 0);
    
        //merge cell A1 until C3
        sheetLapTrx.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
    }
    
  3. How to set font style
    public void doSample(){
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheetLapTrx = workbook.createSheet("Sample Sheet");
        row = sheetLapTrx.createRow(0);
        cell = row.createCell((short) 0);
    
        XSSFCellStyle style = (XSSFCellStyle)workbook.createCellStyle();
        XSSFFont font = workbook.createFont();
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style.setFont(font);
    
        cell.setCellStyle(style);
    }
    
  4. How to make border
    public void doSample(){
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheetLapTrx = workbook.createSheet("Sample Sheet");
        row = sheetLapTrx.createRow(0);
        cell = row.createCell((short) 0);
    
        XSSFCellStyle style = (XSSFCellStyle)workbook.createCellStyle();
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBorderTop(CellStyle.BORDER_THIN);
    
        cell.setCellStyle(style);
    }
    
  5. How to set text alignment
    public void doSample(){
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheetLapTrx = workbook.createSheet("Sample Sheet");
        row = sheetLapTrx.createRow(0);
        cell = row.createCell((short) 0);
    
        XSSFCellStyle style = (XSSFCellStyle)workbook.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER);
    
        cell.setCellStyle(style);
    }
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s