Java 类org.apache.poi.xssf.usermodel.XSSFDataFormat 实例源码

项目:app-framework    文件:TableExcelRenderer.java   
/**
 * Render the specified table
 * 
 * @param table the table view
 * @param formatted
 *            true if a formatting must be applied
 * @return a byte array (Excel file)
 */
private static byte[] render(Table<?> table, boolean formatted) {
    XSSFWorkbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet("export");

    // Default date format
    XSSFCellStyle dateCellStyle = wb.createCellStyle();
    XSSFDataFormat df = wb.createDataFormat();
    dateCellStyle.setDataFormat(df.getFormat(DEFAULT_EXCEL_DATE_FORMAT));

    // Write the header
    Row headerRow = sheet.createRow(0);
    int columnIndex = 0;
    CellStyle headerCellStyle = wb.createCellStyle();
    Font f = wb.createFont();
    f.setBoldweight(Font.BOLDWEIGHT_BOLD);
    headerCellStyle.setFont(f);
    for (ColumnDef header : table.getHeaders()) {
        Cell cell = headerRow.createCell(columnIndex);
        cell.setCellValue(Msg.get(header.getLabel()));
        cell.setCellStyle(headerCellStyle);
        columnIndex++;
    }

    // Write the cells
    if (formatted) {
        writeFormattedRows(table, sheet, dateCellStyle);
    } else {
        writeNotFormattedRows(table, sheet, dateCellStyle);
    }

    ByteArrayOutputStream outBuffer;
    try {
        outBuffer = new ByteArrayOutputStream();
        wb.write(outBuffer);
        outBuffer.close();
    } catch (Exception e) {
        log.error("Error while generating an Excel file from a Table", e);
        throw new RuntimeException("Error while generating an Excel file from a Table", e);
    }
    return outBuffer.toByteArray();
}