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

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

Introduction

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

Prototype

HorizontalAlignment getAlignment();

Source Link

Document

get the type of horizontal alignment for the cell

Usage

From source file:cn.edu.zucc.chenxg.preview.ToHtml.java

License:Apache License

private void styleContents(CellStyle style) {
    styleOut("text-align", style.getAlignment(), ALIGN);
    styleOut("vertical-align", style.getAlignment(), VERTICAL_ALIGN);
    fontStyle(style);/*from  ww w  .j  a  v  a  2  s .c  om*/
    borderStyles(style);
    helper.colorStyles(style, out);
}

From source file:cn.edu.zucc.chenxg.preview.ToHtml.java

License:Apache License

private String tagStyle(Cell cell, CellStyle style) {
    if (style.getAlignment() == ALIGN_GENERAL) {
        switch (ultimateCellType(cell)) {
        case HSSFCell.CELL_TYPE_STRING:
            return "style=\"text-align: left;\"";
        case HSSFCell.CELL_TYPE_BOOLEAN:
        case HSSFCell.CELL_TYPE_ERROR:
            return "style=\"text-align: center;\"";
        case HSSFCell.CELL_TYPE_NUMERIC:
        default://from   w  w  w. j  a  va 2s.  c  o m
            // "right" is the default
            break;
        }
    }
    return "";
}

From source file:com.canoo.webtest.plugins.exceltest.ExcelVerifyCellStyle.java

License:Open Source License

public void doExecute() throws Exception {
    final String[] border = separateSides(getBorder());
    final String[] borderColor = separateSides(getBorderColor());
    for (int i = 0; i < SIDES.length; i++) {
        checkFormat(SIDES[i] + "Border", border[i], getCellBorder(i));
        checkFormat(SIDES[i] + "BorderColor", ExcelColorUtils.lookupStandardColorName(borderColor[i]),
                getCellBorderColor(i));/*  w  w w. ja  v  a2  s.c  o  m*/
    }
    final Cell excelCell = getExcelCell();
    checkFormat("type", getType(),
            ExcelCellUtils.getCellType(excelCell == null ? Cell.CELL_TYPE_BLANK : excelCell.getCellType()));
    if (excelCell == null) {
        if (cellNotRequired()) {
            return;
        } else {
            throw new StepExecutionException("Can't find cell for " + getCellReferenceStr(), this);
        }
    }
    final CellStyle cellStyle = excelCell.getCellStyle();
    checkFormat("format", getFormat(),
            getExcelWorkbook().createDataFormat().getFormat(cellStyle.getDataFormat()));
    checkFormat("align", getAlign(), ExcelCellUtils.getAlignmentString(cellStyle.getAlignment()));
    checkFormat("valign", getValign(),
            ExcelCellUtils.getVerticalAlignmentString(cellStyle.getVerticalAlignment()));
    checkFormat("wrap", getWrap(), String.valueOf(cellStyle.getWrapText()));
    checkFormat("locked", getLocked(), String.valueOf(cellStyle.getLocked()));
    checkFormat("fontName", getFontName(), getFont(cellStyle).getFontName());
    checkFormat("fontSize", getFontSize(), String.valueOf(getFont(cellStyle).getFontHeightInPoints()));
    checkFormat("fontStyle", sortElements(getFontStyle()), getFontStyle(getFont(cellStyle)));
    checkFormat("fillColor", ExcelColorUtils.lookupStandardColorName(getFillColor()),
            ExcelColorUtils.getColorName(this, cellStyle.getFillForegroundColorColor()));
    checkFormat("fillBackgroundColor", ExcelColorUtils.lookupStandardColorName(getFillBackgroundColor()),
            ExcelColorUtils.getColorName(this, cellStyle.getFillBackgroundColorColor()));
    checkFormat("textColor", ExcelColorUtils.lookupStandardColorName(getTextColor()),
            ExcelColorUtils.getColorName(this, getFont(cellStyle).getColor()));
    checkFormat("fillPattern", getFillPattern(), ExcelCellUtils.getFillPattern(cellStyle.getFillPattern()));
}

From source file:com.ncc.excel.test.ExcelUtil.java

License:Apache License

/** 
 * ????? /*from  w ww.  ja v  a2  s  .c  o m*/
 *  
 * @param fromStyle 
 * @param toStyle 
 */
public static void copyCellStyle(CellStyle fromStyle, CellStyle toStyle) {
    toStyle.setAlignment(fromStyle.getAlignment());
    //   
    toStyle.setBorderBottom(fromStyle.getBorderBottom());
    toStyle.setBorderLeft(fromStyle.getBorderLeft());
    toStyle.setBorderRight(fromStyle.getBorderRight());
    toStyle.setBorderTop(fromStyle.getBorderTop());
    toStyle.setTopBorderColor(fromStyle.getTopBorderColor());
    toStyle.setBottomBorderColor(fromStyle.getBottomBorderColor());
    toStyle.setRightBorderColor(fromStyle.getRightBorderColor());
    toStyle.setLeftBorderColor(fromStyle.getLeftBorderColor());

    // ?  
    toStyle.setFillBackgroundColor(fromStyle.getFillBackgroundColor());
    toStyle.setFillForegroundColor(fromStyle.getFillForegroundColor());

    // ??  
    toStyle.setDataFormat(fromStyle.getDataFormat());
    toStyle.setFillPattern(fromStyle.getFillPattern());
    // toStyle.setFont(fromStyle.getFont(null));  
    toStyle.setHidden(fromStyle.getHidden());
    toStyle.setIndention(fromStyle.getIndention());//   
    toStyle.setLocked(fromStyle.getLocked());
    toStyle.setRotation(fromStyle.getRotation());//   
    toStyle.setVerticalAlignment(fromStyle.getVerticalAlignment());
    toStyle.setWrapText(fromStyle.getWrapText());

}

From source file:com.vaadin.addon.spreadsheet.CellValueManager.java

License:Open Source License

protected CellData createCellDataForCell(Cell cell) {
    CellData cellData = new CellData();
    cellData.row = cell.getRowIndex() + 1;
    cellData.col = cell.getColumnIndex() + 1;
    CellStyle cellStyle = cell.getCellStyle();
    cellData.cellStyle = "cs" + cellStyle.getIndex();
    cellData.locked = spreadsheet.isCellLocked(cell);
    try {// w ww.j a  v  a2  s .c o m
        if (!spreadsheet.isCellHidden(cell)) {
            if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                cellData.formulaValue = formulaFormatter.reFormatFormulaValue(cell.getCellFormula(),
                        spreadsheet.getLocale());
                try {
                    String oldValue = getCachedFormulaCellValue(cell);
                    String newValue = formatter.formatCellValue(cell, getFormulaEvaluator());
                    if (!newValue.equals(oldValue)) {
                        changedFormulaCells.add(new CellReference(cell));
                    }
                } catch (RuntimeException rte) {
                    // Apache POI throws RuntimeExceptions for an invalid
                    // formula from POI model
                    String formulaValue = cell.getCellFormula();
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    cell.setCellValue(formulaValue);
                    spreadsheet.markInvalidFormula(cell.getColumnIndex() + 1, cell.getRowIndex() + 1);
                }

            }
        }

        if (cell.getCellStyle().getDataFormatString().contains("%")) {
            cellData.isPercentage = true;
        }

        String formattedCellValue = formatter.formatCellValue(cell, getFormulaEvaluator());

        if (!spreadsheet.isCellHidden(cell)) {
            if (cell.getCellType() == Cell.CELL_TYPE_FORMULA || cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                formattedCellValue = formattedCellValue.replaceAll("^-(?=0(.0*)?$)", "");
            }
        }
        if (spreadsheet.isMarkedAsInvalidFormula(cellData.col, cellData.row)) {
            // The prefix '=' or '+' should not be included in formula value
            if (cell.getStringCellValue().charAt(0) == '+' || cell.getStringCellValue().charAt(0) == '=') {
                cellData.formulaValue = cell.getStringCellValue().substring(1);
            }
            formattedCellValue = "#VALUE!";
        }

        if (formattedCellValue != null && !formattedCellValue.isEmpty() || cellStyle.getIndex() != 0) {
            // if the cell is not wrapping text, and is of type numeric or
            // formula (but not date), calculate if formatted cell value
            // fits the column width and possibly use scientific notation.
            cellData.value = formattedCellValue;
            cellData.needsMeasure = false;
            if (!cellStyle.getWrapText()
                    && (!SpreadsheetUtil.cellContainsDate(cell) && cell.getCellType() == Cell.CELL_TYPE_NUMERIC
                            || cell.getCellType() == Cell.CELL_TYPE_STRING
                            || (cell.getCellType() == Cell.CELL_TYPE_FORMULA
                                    && !cell.getCellFormula().startsWith("HYPERLINK")))) {
                if (!doesValueFit(cell, formattedCellValue)) {
                    if (valueContainsOnlyNumbers(formattedCellValue) && isGenerallCell(cell)) {
                        cellData.value = cellValueFormatter.getScientificNotationStringForNumericCell(
                                cell.getNumericCellValue(), formattedCellValue,
                                cellStyleWidthRatioMap.get((int) cell.getCellStyle().getIndex()),
                                spreadsheet.getState(false).colW[cell.getColumnIndex()] - 10);
                    } else if (cell.getCellType() != Cell.CELL_TYPE_STRING) {
                        cellData.needsMeasure = true;
                    }
                }
            }

            if (cellStyle.getAlignment() == CellStyle.ALIGN_RIGHT) {
                cellData.cellStyle = cellData.cellStyle + " r";
            } else if (cellStyle.getAlignment() == CellStyle.ALIGN_GENERAL) {
                if (SpreadsheetUtil.cellContainsDate(cell) || cell.getCellType() == Cell.CELL_TYPE_NUMERIC
                        || (cell.getCellType() == Cell.CELL_TYPE_FORMULA
                                && !cell.getCellFormula().startsWith("HYPERLINK")
                                && !(cell.getCachedFormulaResultType() == Cell.CELL_TYPE_STRING))) {
                    cellData.cellStyle = cellData.cellStyle + " r";
                }
            }

        }

        // conditional formatting might be applied even if there isn't a
        // value (such as borders for the cell to the right)
        Set<Integer> cellFormattingIndexes = spreadsheet.getConditionalFormatter().getCellFormattingIndex(cell);
        if (cellFormattingIndexes != null) {

            for (Integer i : cellFormattingIndexes) {
                cellData.cellStyle = cellData.cellStyle + " cf" + i;
            }

            markedCells.add(SpreadsheetUtil.toKey(cell));
        }

        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC && DateUtil.isCellDateFormatted(cell)) {
            cellData.originalValue = cellData.value;
        } else {
            cellData.originalValue = getOriginalCellValue(cell);
        }

        handleIsDisplayZeroPreference(cell, cellData);
    } catch (RuntimeException rte) {
        LOGGER.log(Level.FINEST, rte.getMessage(), rte);
        cellData.value = "#VALUE!";
    }

    return cellData;
}

From source file:com.vaadin.addon.spreadsheet.SpreadsheetStyleFactory.java

License:Open Source License

/**
 * Reloads all sheet and cell styles from the current Workbook.
 *///from   ww w  . j  ava  2s  .  com
public void reloadWorkbookStyles() {
    final Workbook workbook = spreadsheet.getWorkbook();
    if (spreadsheet.getState().cellStyleToCSSStyle == null) {
        spreadsheet.getState().cellStyleToCSSStyle = new HashMap<Integer, String>(workbook.getNumCellStyles());
    } else {
        spreadsheet.getState().cellStyleToCSSStyle.clear();
    }
    shiftedBorderLeftStyles.clear();
    shiftedBorderTopStyles.clear();
    mergedCellBorders.clear();

    // get default text alignments
    CellStyle cellStyle = workbook.getCellStyleAt((short) 0);
    defaultTextAlign = cellStyle.getAlignment();
    // defaultVerticalAlign = cellStyle.getVerticalAlignment();

    // create default style (cell style 0)
    StringBuilder sb = new StringBuilder();
    borderStyles(sb, cellStyle);
    defaultFontStyle(cellStyle, sb);
    colorConverter.defaultColorStyles(cellStyle, sb);
    spreadsheet.getState().cellStyleToCSSStyle.put((int) cellStyle.getIndex(), sb.toString());

    // 0 is default style, create all styles indexed from 1 and upwards
    for (short i = 1; i < workbook.getNumCellStyles(); i++) {
        cellStyle = workbook.getCellStyleAt(i);
        addCellStyleCSS(cellStyle);
    }
    reloadActiveSheetColumnRowStyles();
}

From source file:com.vaadin.addon.spreadsheet.SpreadsheetStyleFactory.java

License:Open Source License

private void addCellStyleCSS(CellStyle cellStyle) {

    if (cellStyle.getIndex() == 0) {
        // default cell style, do not change.
        return;//  w ww. j  a v a2s.co m
    }

    StringBuilder sb = new StringBuilder();

    fontStyle(sb, cellStyle);
    colorConverter.colorStyles(cellStyle, sb);
    borderStyles(sb, cellStyle);
    if (cellStyle.getAlignment() != defaultTextAlign) {
        styleOut(sb, "text-align", cellStyle.getAlignment(), ALIGN);
        // TODO For correct overflow, rtl should be used for right align
        // if (cellStyle.getAlignment() == ALIGN_RIGHT) {
        // sb.append("direction:rtl;");
        // }
    }

    // excel default is bottom, so that is what we have in the CSS base
    // files.
    // TODO This only works on modern (10+) IE.
    styleOut(sb, "justify-content", cellStyle.getVerticalAlignment(), VERTICAL_ALIGN);

    if (cellStyle.getWrapText()) { // default is to overflow
        sb.append("overflow:hidden;white-space:normal;");
    }

    if (cellStyle.getIndention() > 0) {
        sb.append("padding-left: " + cellStyle.getIndention() + "em;");
    }

    spreadsheet.getState().cellStyleToCSSStyle.put((int) cellStyle.getIndex(), sb.toString());
}

From source file:egovframework.rte.fdl.excel.EgovExcelServiceTest.java

License:Apache License

/**
 * [Flow #-3]  ? ?  :  ?? ?(? ?, Border? ?, ? ?,  )? 
 *//*from w w w.ja va2  s .c om*/
@Test
public void testWriteExcelFileAttribute() throws Exception {

    try {
        LOGGER.debug("testWriteExcelFileAttribute start....");

        short rowheight = 40 * 10;
        int columnwidth = 30;

        StringBuffer sb = new StringBuffer();
        sb.append(fileLocation).append("/").append("testWriteExcelFileAttribute.xls");

        // delete file
        if (EgovFileUtil.isExistsFile(sb.toString())) {
            EgovFileUtil.delete(new File(sb.toString()));

            LOGGER.debug("Delete file....{}", sb.toString());
        }

        Workbook wb = new HSSFWorkbook();

        Sheet sheet1 = wb.createSheet("new sheet");
        wb.createSheet("second sheet");

        // ? ?
        sheet1.setDefaultRowHeight(rowheight);
        sheet1.setDefaultColumnWidth(columnwidth);

        Font f2 = wb.createFont();
        CellStyle cs = wb.createCellStyle();
        cs = wb.createCellStyle();

        cs.setFont(f2);
        cs.setWrapText(true);

        // 
        cs.setAlignment(CellStyle.ALIGN_RIGHT);

        cs.setFillPattern(CellStyle.DIAMONDS); //  ?

        // ? ?
        cs.setFillForegroundColor(new HSSFColor.BLUE().getIndex()); //  
        cs.setFillBackgroundColor(new HSSFColor.RED().getIndex()); // 

        sheet1.setDefaultColumnStyle((short) 0, cs);

        Workbook tmp = excelService.createWorkbook(wb, sb.toString());

        Sheet sheetTmp1 = tmp.getSheetAt(0);

        assertEquals(rowheight, sheetTmp1.getDefaultRowHeight());
        assertEquals(columnwidth, sheetTmp1.getDefaultColumnWidth());

        CellStyle cs1 = tmp.getCellStyleAt((short) (tmp.getNumCellStyles() - 1));

        LOGGER.debug("getAlignment : {}", cs1.getAlignment());
        assertEquals(CellStyle.ALIGN_RIGHT, cs1.getAlignment());

        LOGGER.debug("getFillPattern : {}", cs1.getFillPattern());
        assertEquals(CellStyle.DIAMONDS, cs1.getFillPattern());

        LOGGER.debug("getFillForegroundColor : {}", cs1.getFillForegroundColor());
        LOGGER.debug("getFillBackgroundColor : {}", cs1.getFillBackgroundColor());
        assertEquals(new HSSFColor.BLUE().getIndex(), cs1.getFillForegroundColor());
        assertEquals(new HSSFColor.RED().getIndex(), cs1.getFillBackgroundColor());

    } catch (Exception e) {
        LOGGER.error(e.toString());
        throw new Exception(e);
    } finally {
        LOGGER.debug("testWriteExcelFileAttribute end....");
    }
}

From source file:egovframework.rte.fdl.excel.EgovExcelServiceTest.java

License:Apache License

/**
 * [Flow #-6]  ?  :  ? ?(?, ? )? // w  w w .  java 2  s  . com
 */
@Test
public void testModifyCellAttribute() throws Exception {

    try {
        LOGGER.debug("testModifyCellAttribute start....");

        StringBuffer sb = new StringBuffer();
        sb.append(fileLocation).append("/").append("testModifyCellAttribute.xls");

        if (EgovFileUtil.isExistsFile(sb.toString())) {
            EgovFileUtil.delete(new File(sb.toString()));

            LOGGER.debug("Delete file....{}", sb.toString());
        }

        Workbook wbTmp = new HSSFWorkbook();
        wbTmp.createSheet();

        //  ? ?
        excelService.createWorkbook(wbTmp, sb.toString());

        //  ? 
        Workbook wb = excelService.loadWorkbook(sb.toString());
        LOGGER.debug("testModifyCellAttribute after loadWorkbook....");

        Sheet sheet = wb.createSheet("cell test sheet2");
        //           sheet.setColumnWidth((short) 3, (short) 200);   // column Width

        CellStyle cs = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontHeight((short) 16);
        font.setBoldweight((short) 3);
        font.setFontName("fixedsys");

        cs.setFont(font);
        cs.setAlignment(CellStyle.ALIGN_RIGHT); // cell 
        cs.setWrapText(true);

        for (int i = 0; i < 100; i++) {
            Row row = sheet.createRow(i);
            //              row.setHeight((short)300); // row? height 

            for (int j = 0; j < 5; j++) {
                Cell cell = row.createCell(j);
                cell.setCellValue(new HSSFRichTextString("row " + i + ", cell " + j));
                cell.setCellStyle(cs);
            }
        }

        //  ? 
        FileOutputStream out = new FileOutputStream(sb.toString());
        wb.write(out);
        out.close();

        //////////////////////////////////////////////////////////////////////////
        // ?
        Workbook wbT = excelService.loadWorkbook(sb.toString());
        Sheet sheetT = wbT.getSheet("cell test sheet2");
        LOGGER.debug("getNumCellStyles : {}", wbT.getNumCellStyles());

        CellStyle cs1 = wbT.getCellStyleAt((short) (wbT.getNumCellStyles() - 1));

        Font fontT = ((HSSFCellStyle) cs1).getFont(wbT);
        LOGGER.debug("font getFontHeight : {}", fontT.getFontHeight());
        LOGGER.debug("font getBoldweight : {}", fontT.getBoldweight());
        LOGGER.debug("font getFontName : {}", fontT.getFontName());
        LOGGER.debug("getAlignment : {}", cs1.getAlignment());
        LOGGER.debug("getWrapText : {}", cs1.getWrapText());

        for (int i = 0; i < 100; i++) {
            Row row1 = sheetT.getRow(i);
            for (int j = 0; j < 5; j++) {
                Cell cell1 = row1.getCell(j);
                LOGGER.debug("row {}, cell {} : {}", i, j, cell1.getRichStringCellValue());
                assertEquals(16, fontT.getFontHeight());
                assertEquals(3, fontT.getBoldweight());
                assertEquals(CellStyle.ALIGN_RIGHT, cs1.getAlignment());
                assertTrue(cs1.getWrapText());
            }
        }

    } catch (Exception e) {
        LOGGER.error(e.toString());
        throw new Exception(e);
    } finally {
        LOGGER.debug("testModifyCellAttribute end....");
    }
}

From source file:egovframework.rte.fdl.excel.EgovExcelSXSSFServiceTest.java

License:Apache License

/**
 * [Flow #-3]  ? ?  :  ?? ?(? ?, Border? ?, ? ?,  )? 
 *///from   w  w  w  .  ja  v a 2  s . c o  m
@Test
public void testWriteExcelFileAttribute() throws Exception {

    try {
        log.debug("testWriteExcelFileAttribute start....");

        short rowheight = 40;
        int columnwidth = 30;

        StringBuffer sb = new StringBuffer();
        sb.append(fileLocation).append("/").append("testWriteExcelFileAttribute.xlsx");

        // delete file
        if (EgovFileUtil.isExistsFile(sb.toString())) {
            EgovFileUtil.delete(new File(sb.toString()));

            log.debug("Delete file...." + sb.toString());
        }

        SXSSFWorkbook wb = new SXSSFWorkbook();

        Sheet sheet1 = wb.createSheet("new sheet");
        wb.createSheet("second sheet");

        // ? ?
        sheet1.setDefaultRowHeight(rowheight);
        sheet1.setDefaultColumnWidth(columnwidth);

        Font f2 = wb.createFont();
        CellStyle cs = wb.createCellStyle();
        cs = wb.createCellStyle();

        cs.setFont(f2);
        cs.setWrapText(true);

        // 
        cs.setAlignment(HSSFCellStyle.ALIGN_RIGHT);

        cs.setFillPattern(HSSFCellStyle.DIAMONDS); //  ?

        // ? ?
        cs.setFillForegroundColor(new HSSFColor.BLUE().getIndex()); //  
        cs.setFillBackgroundColor(new HSSFColor.RED().getIndex()); // 

        sheet1.setDefaultColumnStyle((short) 0, cs);

        Workbook tmp = excelService.createSXSSFWorkbook(wb, sb.toString());

        Sheet sheetTmp1 = tmp.getSheetAt(0);

        assertEquals(rowheight, sheetTmp1.getDefaultRowHeight());
        assertEquals(columnwidth, sheetTmp1.getDefaultColumnWidth());

        CellStyle cs1 = tmp.getCellStyleAt((short) (tmp.getNumCellStyles() - 1));

        log.debug("getAlignment : " + cs1.getAlignment());
        assertEquals(HSSFCellStyle.ALIGN_RIGHT, cs1.getAlignment());

        log.debug("getFillPattern : " + cs1.getFillPattern());
        assertEquals(HSSFCellStyle.DIAMONDS, cs1.getFillPattern());

        log.debug("getFillForegroundColor : " + cs1.getFillForegroundColor());
        log.debug("getFillBackgroundColor : " + cs1.getFillBackgroundColor());
        assertEquals(new HSSFColor.BLUE().getIndex(), cs1.getFillForegroundColor());
        assertEquals(new HSSFColor.RED().getIndex(), cs1.getFillBackgroundColor());

    } catch (Exception e) {
        log.error(e.toString());
        throw new Exception(e);
    } finally {
        log.debug("testWriteExcelFileAttribute end....");
    }
}