Friday, November 18, 2011

Apache POI-XSSF

Set background color of a cell:

CellStyle result = workbook.createCellStyle();
result.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
result.setFillPattern(CellStyle.SOLID_FOREGROUND);


Merge some cells together:


/**
 * Merge the cells into one
 *
 * @param sheet
 * @param rowNum
 * @param fromCellNum 0-based index
 * @param toCellNum 0-based index
 */
private static void mergeCells(Sheet sheet, int rowNum, 
                                     int fromCellNum, int toCellNum) {
    sheet.addMergedRegion(
              new CellRangeAddress(rowNum, rowNum, fromCellNum, toCellNum));
}


Set a comment:

/**
 * Set a comment on a cell.
 *
 * @param text
 * @param cell
 */
private static void setComment(String text, Cell cell) {
    // Numbers on Mac OS hands the comment much, much better than Excel.  
    // Ugh to Excel!
       
    Sheet sheet = cell.getSheet();
    Row row = cell.getRow();
    Workbook wb = sheet.getWorkbook();
       
    CreationHelper createHelper = wb.getCreationHelper();

    Drawing drawing = sheet.createDrawingPatriarch();
       
    // count the number of lines in the comment.  
    // use this to decide how many rows down to anchor the comment box.
    // Note: there may be a better way to do it.  just playing around for now.
    int lineCount = getLineCount(text);
       
    ClientAnchor anchor = createHelper.createClientAnchor();
       
    anchor.setCol1(cell.getColumnIndex());
    anchor.setCol2(cell.getColumnIndex()+10);
    anchor.setRow1(row.getRowNum());
    anchor.setRow2(row.getRowNum()+lineCount);
        
    Comment comment = drawing.createCellComment(anchor);
    RichTextString str = createHelper.createRichTextString(StringUtils.strip(text));

    // without the font set, the comment would not appear at all!
    Font font = wb.createFont();
    font.setFontName( "Arial" );
       
    str.applyFont(font);

    comment.setString(str);
       
    cell.setCellComment(comment);
}

No comments:

Post a Comment