Example usage for org.apache.poi.ss.usermodel CellStyle setDataFormat

List of usage examples for org.apache.poi.ss.usermodel CellStyle setDataFormat

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel CellStyle setDataFormat.

Prototype

void setDataFormat(short fmt);

Source Link

Document

set the data format (must be a valid format).

Usage

From source file:PlacasClientes.java

private void EnviarExcel(ResultSet rs) throws IOException {
    String rutaArchivo = System.getProperty("user.home") + "/ejemploExcelJava.xls";
    /*Se crea el objeto de tipo File con la ruta del archivo*/
    File archivoXLS = new File(rutaArchivo);
    /*Si el archivo existe se elimina*/
    if (archivoXLS.exists())
        archivoXLS.delete();//from ww w .  j av a  2  s .co m
    /*Se crea el archivo*/
    archivoXLS.createNewFile();

    /*Se crea el libro de excel usando el objeto de tipo Workbook*/
    Workbook libro = new HSSFWorkbook();
    CreationHelper createhelper = libro.getCreationHelper();
    CellStyle cellStyle = libro.createCellStyle();
    cellStyle.setDataFormat(createhelper.createDataFormat().getFormat("dd/mm/yyyy"));
    CellStyle cellStyle2 = libro.createCellStyle();

    /*Se inicializa el flujo de datos con el archivo xls*/
    FileOutputStream archivo = new FileOutputStream(archivoXLS);

    /*Utilizamos la clase Sheet para crear una nueva hoja de trabajo dentro del libro que creamos anteriormente*/
    Sheet hoja = libro.createSheet("ClientesPlacas");

    Font fuente = libro.createFont();
    fuente.setFontHeightInPoints((short) 13);
    fuente.setFontName("Arial");
    fuente.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

    Font fuente2 = libro.createFont();
    fuente.setFontHeightInPoints((short) 13);
    fuente.setFontName("Arial");
    //fuente.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

    Row Enc = hoja.createRow(2);
    Cell celda = Enc.createCell(0);

    celda.setCellValue("PLACA DE VEHICULOS POR CLIENTES");

}

From source file:adams.core.ExcelHelper.java

License:Open Source License

/**
 * Creates a cellstyle for a date cell with the specified format.
 * /* w  w w  .  j  a  v  a  2s .  c om*/
 * @param wb      the workbook to use this format for
 * @param format   the format to use
 * @return      the generated style
 */
public static CellStyle getDateCellStyle(Workbook wb, String format) {
    CellStyle result;

    result = wb.createCellStyle();
    result.setDataFormat(wb.createDataFormat().getFormat(format));

    return result;
}

From source file:apm.common.utils.excel.ExportExcel.java

License:Open Source License

/**
 * ?/*from   w w  w.j  a va  2  s. com*/
 * @param row 
 * @param column ?
 * @param val 
 * @param align ??1?23??
 * @return ?
 */
public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType) {
    Cell cell = row.createCell(column);
    CellStyle style = styles.get("data" + (align >= 1 && align <= 3 ? align : ""));
    try {
        if (val == null) {
            cell.setCellValue("");
        } else if (val instanceof String) {
            cell.setCellValue((String) val);
        } else if (val instanceof Integer) {
            cell.setCellValue((Integer) val);
        } else if (val instanceof Long) {
            cell.setCellValue((Long) val);
        } else if (val instanceof Double) {
            cell.setCellValue((Double) val);
        } else if (val instanceof Float) {
            cell.setCellValue((Float) val);
        } else if (val instanceof Date) {
            DataFormat format = wb.createDataFormat();
            style.setDataFormat(format.getFormat("yyyy-MM-dd"));
            cell.setCellValue((Date) val);
        } else {
            if (fieldType != Class.class) {
                cell.setCellValue((String) fieldType.getMethod("setValue", Object.class).invoke(null, val));
            } else {
                cell.setCellValue((String) Class
                        .forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
                                "fieldtype." + val.getClass().getSimpleName() + "Type"))
                        .getMethod("setValue", Object.class).invoke(null, val));
            }
        }
    } catch (Exception ex) {
        log.info("Set cell value [" + row.getRowNum() + "," + column + "] error: " + ex.toString());
        cell.setCellValue(val.toString());
    }
    cell.setCellStyle(style);
    return cell;
}

From source file:bad.robot.excel.cell.DataFormat.java

License:Apache License

private void updateDataFormat(Cell cell, Workbook workbook) {
    CellStyle style = newStyleBasedOn(cell).create(workbook);
    style.setDataFormat(workbook.createDataFormat().getFormat(value()));
    cell.setCellStyle(style);/* w w  w  .j  a va2 s .c  o  m*/
}

From source file:bad.robot.excel.matchers.StubCell.java

License:Apache License

static Cell createCell(int row, int column, Date date) {
    Workbook workbook = new HSSFWorkbook();
    Sheet sheet = workbook.createSheet();
    Cell cell = sheet.createRow(row).createCell(column, CELL_TYPE_NUMERIC);
    cell.setCellValue(date);//from w  w w .  j  av a2 s  . c  o m
    CellStyle style = workbook.createCellStyle();
    style.setDataFormat(workbook.getCreationHelper().createDataFormat().getFormat("m/d/yy h:mm"));
    cell.setCellStyle(style);
    return cell;
}

From source file:bad.robot.excel.style.ReplaceExistingStyle.java

License:Apache License

private void applyDataFormatTo(CellStyle style, Workbook workbook) {
    if (format != null)
        style.setDataFormat(workbook.createDataFormat().getFormat(format.value()));
}

From source file:bandaru_excelreadwrite.WritetoExcel.java

public void writeSongsListToExcel(List<Song> songList) {

    /*//from ww  w  . ja v a 2s.  com
    Use XSSF for xlsx format and for xls use HSSF
     */
    Workbook workbook = new XSSFWorkbook();

    /*
    create new sheet 
     */
    Sheet songsSheet = workbook.createSheet("Albums");

    XSSFCellStyle my_style = (XSSFCellStyle) workbook.createCellStyle();
    /* Create XSSFFont object from the workbook */
    XSSFFont my_font = (XSSFFont) workbook.createFont();

    /*
    setting cell color
     */
    CellStyle style = workbook.createCellStyle();
    style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);

    /*
     setting Header color
     */
    CellStyle style2 = workbook.createCellStyle();
    style2.setFillForegroundColor(IndexedColors.DARK_RED.getIndex());
    style2.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style2.setAlignment(style2.ALIGN_CENTER);

    Row rowName = songsSheet.createRow(1);

    /*
    Merging the cells
     */
    songsSheet.addMergedRegion(new CellRangeAddress(1, 1, 2, 3));

    /*
    Applying style to attribute name
     */
    int nameCellIndex = 1;
    Cell namecell = rowName.createCell(nameCellIndex++);
    namecell.setCellValue("Name");
    namecell.setCellStyle(style);

    Cell cel = rowName.createCell(nameCellIndex++);
    cel.setCellValue("Bandaru, Sreekanth");

    /*
    Applying underline to Name
     */
    my_font.setUnderline(XSSFFont.U_SINGLE);
    my_style.setFont(my_font);
    /* Attaching the style to the cell */
    CellStyle combined = workbook.createCellStyle();
    combined.cloneStyleFrom(my_style);
    combined.cloneStyleFrom(style);
    combined.setAlignment(combined.ALIGN_CENTER);

    cel.setCellStyle(combined);

    /*
    Applying  colors to header 
     */
    Row rowMain = songsSheet.createRow(3);
    SheetConditionalFormatting sheetCF = songsSheet.getSheetConditionalFormatting();
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("3");

    PatternFormatting fill1 = rule1.createPatternFormatting();
    fill1.setFillBackgroundColor(IndexedColors.LIME.index);
    fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regions = { CellRangeAddress.valueOf("A4:F4") };

    sheetCF.addConditionalFormatting(regions, rule1);

    /*
    setting new rule to apply alternate colors to cells having same Genre
     */
    ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule("4");
    PatternFormatting fill2 = rule2.createPatternFormatting();
    fill2.setFillBackgroundColor(IndexedColors.LEMON_CHIFFON.index);
    fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regionsAction = { CellRangeAddress.valueOf("A5:F5"), CellRangeAddress.valueOf("A6:F6"),
            CellRangeAddress.valueOf("A7:F7"), CellRangeAddress.valueOf("A8:F8"),
            CellRangeAddress.valueOf("A13:F13"), CellRangeAddress.valueOf("A14:F14"),
            CellRangeAddress.valueOf("A15:F15"), CellRangeAddress.valueOf("A16:F16"),
            CellRangeAddress.valueOf("A23:F23"), CellRangeAddress.valueOf("A24:F24"),
            CellRangeAddress.valueOf("A25:F25"), CellRangeAddress.valueOf("A26:F26")

    };

    /*        
    setting new rule to apply alternate colors to cells having same Fenre
     */
    ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule("4");
    PatternFormatting fill3 = rule3.createPatternFormatting();
    fill3.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index);
    fill3.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

    CellRangeAddress[] regionsAdv = { CellRangeAddress.valueOf("A9:F9"), CellRangeAddress.valueOf("A10:F10"),
            CellRangeAddress.valueOf("A11:F11"), CellRangeAddress.valueOf("A12:F12"),
            CellRangeAddress.valueOf("A17:F17"), CellRangeAddress.valueOf("A18:F18"),
            CellRangeAddress.valueOf("A19:F19"), CellRangeAddress.valueOf("A20:F20"),
            CellRangeAddress.valueOf("A21:F21"), CellRangeAddress.valueOf("A22:F22"),
            CellRangeAddress.valueOf("A27:F27"), CellRangeAddress.valueOf("A28:F28"),
            CellRangeAddress.valueOf("A29:F29") };

    /*
    Applying above created rule formatting to cells
     */
    sheetCF.addConditionalFormatting(regionsAction, rule2);
    sheetCF.addConditionalFormatting(regionsAdv, rule3);

    /*
     Setting coloumn header values
     */
    int mainCellIndex = 0;
    CellStyle style4 = workbook.createCellStyle();
    XSSFFont my_font2 = (XSSFFont) workbook.createFont();
    my_font2.setBold(true);
    style4.setFont(my_font2);
    rowMain.setRowStyle(style4);
    rowMain.createCell(mainCellIndex++).setCellValue("SNO");
    rowMain.createCell(mainCellIndex++).setCellValue("Genre");
    rowMain.createCell(mainCellIndex++).setCellValue("Rating");
    rowMain.createCell(mainCellIndex++).setCellValue("Movie Name");
    rowMain.createCell(mainCellIndex++).setCellValue("Director");
    rowMain.createCell(mainCellIndex++).setCellValue("Release Date");

    /*
    populating cell values
     */
    int rowIndex = 4;
    int sno = 1;
    for (Song song : songList) {
        if (song.getSno() != 0) {

            Row row = songsSheet.createRow(rowIndex++);
            int cellIndex = 0;

            /*
            first place in row is Sno
             */
            row.createCell(cellIndex++).setCellValue(sno++);

            /*
            second place in row is  Genre
             */
            row.createCell(cellIndex++).setCellValue(song.getGenre());

            /*
            third place in row is Critic score
             */
            row.createCell(cellIndex++).setCellValue(song.getCriticscore());

            /*
            fourth place in row is Album name
             */
            row.createCell(cellIndex++).setCellValue(song.getAlbumname());

            /*
            fifth place in row is Artist
             */
            row.createCell(cellIndex++).setCellValue(song.getArtist());

            /*
            sixth place in row is marks in date
             */
            if (song.getReleasedate() != null) {

                Cell date = row.createCell(cellIndex++);

                DataFormat format = workbook.createDataFormat();
                CellStyle dateStyle = workbook.createCellStyle();

                dateStyle.setDataFormat(format.getFormat("dd-MMM-yyyy"));
                date.setCellStyle(dateStyle);

                date.setCellValue(song.getReleasedate());

                /*
                auto-resizing columns
                 */
                songsSheet.autoSizeColumn(6);
                songsSheet.autoSizeColumn(5);
                songsSheet.autoSizeColumn(4);
                songsSheet.autoSizeColumn(3);
                songsSheet.autoSizeColumn(2);
            }

        }
    }

    /*
    writing this workbook to excel file.
     */
    try {
        FileOutputStream fos = new FileOutputStream(FILE_PATH);
        workbook.write(fos);
        fos.close();

        System.out.println(FILE_PATH + " is successfully written");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:biz.webgate.dominoext.poi.component.kernel.simpleviewexport.WorkbooklExportProcessor.java

License:Apache License

public void process2HTTP(ExportModel expModel, UISimpleViewExport uis, HttpServletResponse hsr,
        DateTimeHelper dth) {/*from   ww  w. j a  va  2s  .  co  m*/
    try {
        String strFileName = uis.getDownloadFileName();

        Workbook wbCurrent = null;
        if (strFileName.toLowerCase().endsWith(".xlsx")) {
            wbCurrent = new XSSFWorkbook();
        } else {
            wbCurrent = new HSSFWorkbook();
        }
        HashMap<String, CellStyle> hsCS = new HashMap<String, CellStyle>();
        CreationHelper cr = wbCurrent.getCreationHelper();
        CellStyle csDate = wbCurrent.createCellStyle();
        csDate.setDataFormat(cr.createDataFormat().getFormat(dth.getDFDate().toPattern()));

        CellStyle csDateTime = wbCurrent.createCellStyle();
        csDateTime.setDataFormat(cr.createDataFormat().getFormat(dth.getDFDateTime().toPattern()));

        CellStyle csTime = wbCurrent.createCellStyle();
        csTime.setDataFormat(cr.createDataFormat().getFormat(dth.getDFTime().toPattern()));

        hsCS.put("DATE", csDate);
        hsCS.put("TIME", csTime);
        hsCS.put("DATETIME", csDateTime);

        Sheet sh = wbCurrent.createSheet("SVE Export");
        int nRowCount = 0;

        // BUILDING HEADER
        if (uis.isIncludeHeader()) {
            Row rw = sh.createRow(nRowCount);
            int nCol = 0;
            for (ExportColumn expColumn : expModel.getColumns()) {
                rw.createCell(nCol).setCellValue(expColumn.getColumnName());
                nCol++;
            }
            nRowCount++;
        }
        // Processing Values
        for (ExportDataRow expRow : expModel.getRows()) {
            Row rw = sh.createRow(nRowCount);
            int nCol = 0;
            for (ExportColumn expColumn : expModel.getColumns()) {
                Cell clCurrent = rw.createCell(nCol);
                setCellValue(expRow.getValue(expColumn.getPosition()), clCurrent, expColumn, hsCS);
                nCol++;
            }
            nRowCount++;
        }
        for (int nCol = 0; nCol < expModel.getColumns().size(); nCol++) {
            sh.autoSizeColumn(nCol);
        }
        if (strFileName.toLowerCase().endsWith(".xlsx")) {
            hsr.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        } else if (strFileName.toLowerCase().endsWith("xls")) {
            hsr.setContentType("application/vnd.ms-excel");

        } else {
            hsr.setContentType("application/octet-stream");
        }
        hsr.addHeader("Content-disposition", "inline; filename=\"" + strFileName + "\"");
        OutputStream os = hsr.getOutputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        wbCurrent.write(bos);
        bos.writeTo(os);
        os.close();
    } catch (Exception e) {
        ErrorPageBuilder.getInstance().processError(hsr, "Error during SVE-Generation (Workbook Export)", e);
    }
}

From source file:biz.webgate.dominoext.poi.component.kernel.WorkbookProcessor.java

License:Apache License

public void setCellValue(Sheet shProcess, int nRow, int nCol, Object objValue, boolean isFormula,
        PoiCellStyle pCellStyle) {/*from w  ww.  j  a va 2  s.  c  o  m*/
    // Logger logCurrent =
    // LoggerFactory.getLogger(WorkbookProcessor.class.getCanonicalName());

    try {
        Row rw = shProcess.getRow(nRow);
        if (rw == null) {
            // logCurrent.finest("Create Row");
            rw = shProcess.createRow(nRow);
        }
        Cell c = rw.getCell(nCol);
        if (c == null) {
            // logCurrent.finest("Create Cell");
            c = rw.createCell(nCol);
        }
        if (isFormula) {
            c.setCellFormula((String) objValue);
        } else {
            if (objValue instanceof Double) {
                c.setCellValue((Double) objValue);
            } else if (objValue instanceof Integer) {
                c.setCellValue((Integer) objValue);
            } else {
                if (objValue instanceof Date) {
                    c.setCellValue((Date) objValue);
                } else {
                    c.setCellValue("" + objValue);
                }
            }
        }
        // *** STYLE CONFIG Since V 1.1.7 ***

        if (pCellStyle != null) {
            checkStyleConstantValues();
            if (pCellStyle.getCellStyle() != null) {
                c.setCellStyle(pCellStyle.getCellStyle());
            } else {
                CellStyle style = shProcess.getWorkbook().createCellStyle();

                if (pCellStyle.getAlignment() != null)
                    style.setAlignment(m_StyleConstantValues.get(pCellStyle.getAlignment()));

                if (pCellStyle.getBorderBottom() != null)
                    style.setBorderBottom(m_StyleConstantValues.get(pCellStyle.getBorderBottom()));

                if (pCellStyle.getBorderLeft() != null)
                    style.setBorderLeft(m_StyleConstantValues.get(pCellStyle.getBorderLeft()));

                if (pCellStyle.getBorderRight() != null)
                    style.setBorderRight(m_StyleConstantValues.get(pCellStyle.getBorderRight()));

                if (pCellStyle.getBorderTop() != null)
                    style.setBorderTop(m_StyleConstantValues.get(pCellStyle.getBorderTop()));

                if (pCellStyle.getBottomBorderColor() != null)
                    style.setBottomBorderColor(
                            IndexedColors.valueOf(pCellStyle.getBottomBorderColor()).getIndex());

                if (pCellStyle.getDataFormat() != null) {
                    DataFormat format = shProcess.getWorkbook().createDataFormat();
                    style.setDataFormat(format.getFormat(pCellStyle.getDataFormat()));
                }

                if (pCellStyle.getFillBackgroundColor() != null)
                    style.setFillBackgroundColor(
                            IndexedColors.valueOf(pCellStyle.getFillBackgroundColor()).getIndex());

                if (pCellStyle.getFillForegroundColor() != null)
                    style.setFillForegroundColor(
                            IndexedColors.valueOf(pCellStyle.getFillForegroundColor()).getIndex());

                if (pCellStyle.getFillPattern() != null)
                    style.setFillPattern(m_StyleConstantValues.get(pCellStyle.getFillPattern()));

                // Create a new font and alter it.
                Font font = shProcess.getWorkbook().createFont();

                if (pCellStyle.getFontBoldweight() != null)
                    font.setBoldweight(m_StyleConstantValues.get(pCellStyle.getFontBoldweight()));

                if (pCellStyle.getFontColor() != null)
                    font.setColor(IndexedColors.valueOf(pCellStyle.getFontColor()).getIndex());

                if (pCellStyle.getFontHeightInPoints() != 0)
                    font.setFontHeightInPoints(pCellStyle.getFontHeightInPoints());

                if (pCellStyle.getFontName() != null)
                    font.setFontName(pCellStyle.getFontName());

                if (pCellStyle.isFontItalic())
                    font.setItalic(pCellStyle.isFontItalic());

                if (pCellStyle.isFontStrikeout())
                    font.setStrikeout(pCellStyle.isFontStrikeout());

                if (pCellStyle.getFontUnderline() != null)
                    font.setUnderline(m_StyleByteConstantValues.get(pCellStyle.getFontUnderline()));

                if (pCellStyle.getFontTypeOffset() != null)
                    font.setTypeOffset(m_StyleConstantValues.get(pCellStyle.getFontTypeOffset()));

                // Set Font
                style.setFont(font);

                if (pCellStyle.isHidden())
                    style.setHidden(pCellStyle.isHidden());

                if (pCellStyle.getIndention() != null)
                    style.setIndention(m_StyleConstantValues.get(pCellStyle.getIndention()));

                if (pCellStyle.getLeftBorderColor() != null)
                    style.setLeftBorderColor(IndexedColors.valueOf(pCellStyle.getLeftBorderColor()).getIndex());

                if (pCellStyle.isLocked())
                    style.setLocked(pCellStyle.isLocked());

                if (pCellStyle.getRightBorderColor() != null)
                    style.setRightBorderColor(
                            IndexedColors.valueOf(pCellStyle.getRightBorderColor()).getIndex());

                if (pCellStyle.getRotation() != 0)
                    style.setRotation(pCellStyle.getRotation());

                if (pCellStyle.getTopBorderColor() != null)
                    style.setTopBorderColor(IndexedColors.valueOf(pCellStyle.getTopBorderColor()).getIndex());

                if (pCellStyle.getVerticalAlignment() != null)
                    style.setVerticalAlignment(m_StyleConstantValues.get(pCellStyle.getVerticalAlignment()));

                if (pCellStyle.isWrapText())
                    style.setWrapText(pCellStyle.isWrapText());

                c.setCellStyle(style);
                pCellStyle.setCellStyle(style);
            }

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:bo.com.offercruzmail.utils.HojaExcelHelper.java

public void setValorCelda(int rowIndex, int colIndex, Date valor) {
    Cell celda = getCelda(rowIndex, colIndex);
    if (valor != null) {
        celda.setCellValue(valor);// www. j a v a 2s . c  o m
        CreationHelper createHelper = hoja.getWorkbook().getCreationHelper();
        CellStyle estiloFecha = hoja.getWorkbook().createCellStyle();
        estiloFecha.setDataFormat(createHelper.createDataFormat().getFormat("d/m/yy"));
        celda.setCellStyle(estiloFecha);
    }
}