Example usage for org.apache.poi.ss.usermodel Cell getCellStyle

List of usage examples for org.apache.poi.ss.usermodel Cell getCellStyle

Introduction

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

Prototype

CellStyle getCellStyle();

Source Link

Document

Return the cell's style.

Usage

From source file:org.wandora.application.tools.extractors.excel.ExcelAdjacencyMatrixExtractor.java

License:Open Source License

public boolean hasValue(Cell cell) {

    if (ADD_CELL_COLOR_AS_PLAYER || INTERPRET_COLOR_AS_VALID_CELL_VALUE) {
        CellStyle style = cell.getCellStyle();
        short color = style.getFillBackgroundColor();
        if (color != 0) {
            return true;
        }//from  w  w  w  . ja  v a2 s  .  c  o m
    }

    String str = getCellValueAsString(cell);
    if (str == null)
        return false;
    if (INTERPRET_FALSE_AS_EMPTY_CELL && "false".equalsIgnoreCase(str))
        return false;
    if (INTERPRET_ZERO_AS_EMPTY_CELL && "0".equalsIgnoreCase(str))
        return false;
    if (INTERPRET_ZERO_LENGTH_STRING_AS_EMPTY_CELL && "".equalsIgnoreCase(str))
        return false;

    return true;
}

From source file:preprocessing.SkillTextGenerator.java

private static void writeToSheet(Workbook book) {
    Sheet sheet = book.getSheetAt(0);/*  w  ww .  jav  a2 s . c o  m*/
    Row row, styleRow;
    Cell cell, styleCell;
    styleRow = sheet.getRow(1);
    styleCell = styleRow.getCell(0);

    StringBuilder sb;
    String skillId, cellValue, rareLevel = "";
    String[] skillArray, skillArrayBase;
    List<String[]> skillRoleArray;
    int rowCount = 0, colCount;
    for (int n = 0; n < cardList.size(); n++) {
        String[] card = cardList.get(n);
        if (!card[0].matches("[\\d]+[\\d]+")
                || !(card[7].equals("ULTRARARE") || card[7].equals("MILLIONRARE"))) {
            continue;
        }
        if (cardList.size() > n + 1 && card[5].equals(cardList.get(n + 1)[5]) && card[7].equals("ULTRARARE")
                && cardList.get(n + 1)[7].equals("MILLIONRARE")) {
            continue;
        }
        rowCount++;
        colCount = 0;
        row = getNotNullRow(sheet, rowCount);

        // Id, Same Card Id, Normal Skill Id, Bonus Skill Id, Title, Name
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.setCellValue(card[0]);

        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.setCellValue(card[SAME_CARD_ID]);

        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.setCellValue(card[CARD_NORMAL_SKILL]);

        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.setCellValue(card[CARD_BOOST_SKILL]);

        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.setCellValue(card[4]);

        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.setCellValue(card[5]);

        //Rarity, Class, Type, Cost, HP, ATK, INT, MND, Category, Functions
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        if (card[7].equals("ULTRARARE")) {
            rareLevel = "UR";
        } else if (card[7].equals("MILLIONRARE")) {
            rareLevel = "MR";
        }
        cell.setCellValue(rareLevel);

        if (!card[CARD_BOOST_SKILL].isEmpty() && !card[CARD_BOOST_SKILL].equals("0")) {
            skillId = card[CARD_BOOST_SKILL];
        } else {
            skillId = card[CARD_NORMAL_SKILL];
        }

        skillArrayBase = skillMap.get(skillId).get(0);
        skillArray = skillMap.get(skillId).get(skillMap.get(skillId).size() - 1);
        skillRoleArray = skillRoleMap.get(skillArray[SKILL_SKILLROLE_COL]);
        Collections.sort(skillRoleArray, cmp);
        // Class
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.setCellValue(classMap.get(skillArrayBase[11]));
        // Type
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cellValue = getType(skillArrayBase[10]);
        cell.setCellValue(cellValue);
        // Cost
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        if (skillArrayBase[13].matches("[\\d]+")) {
            cell.setCellValue(Integer.parseInt(skillArrayBase[13]));
        } else {
            cell.setCellValue(0);
        }
        // HP
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.setCellValue(Integer.parseInt(card[11]));
        // ATK
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.setCellValue(Integer.parseInt(card[14]));
        // INT
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.setCellValue(Integer.parseInt(card[17]));
        // MND
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.setCellValue(Integer.parseInt(card[20]));
        // Category
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.setCellValue(categoryMap.get(skillArrayBase[9]));
        // Functions
        sb = new StringBuilder();
        for (int j = 0; j < skillRoleArray.size(); j++) {
            sb.append(getFunctionType(skillRoleArray, j)).append("/");
            //sb.append(functionMap.get(skillRoleArray.get(j)[6])).append("/");
        }
        sb.delete(sb.length() - 1, sb.length());
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.setCellValue(sb.toString());
        //System.out.print(colCount);
        // Normal Skill
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.getCellStyle().setAlignment(CellStyle.ALIGN_LEFT);
        cell.setCellValue(getFunctionText(card[CARD_NORMAL_SKILL], rareLevel));
        //System.out.print(";" + colCount);
        // Bonus skill
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.getCellStyle().setAlignment(CellStyle.ALIGN_LEFT);
        cell.setCellValue(sb.toString());
        //System.out.print(";" + colCount);
        // System.out.println(";" + (colCount - 1));
        if (!card[25].isEmpty() && !card[CARD_BOOST_SKILL].equals("0")) {
            cell.setCellValue(getFunctionText(card[CARD_BOOST_SKILL], rareLevel));
        } else {
            cell.setCellValue(row.getCell(colCount - 2).getStringCellValue());
        }

        // Attack Dialogue
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        if (card.length > 84) {
            cell.setCellValue(card[84]);
        } else {
            cell.setCellValue("");
        }
        // Support Dialogue
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        if (card.length > 85) {
            cell.setCellValue(card[85]);
        } else {
            cell.setCellValue("");
        }
        // Image ID
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.setCellValue(card[33]);

        // Description
        cell = getNotNullCell(row, colCount++);
        cell.setCellStyle(styleCell.getCellStyle());
        cell.getCellStyle().setAlignment(CellStyle.ALIGN_LEFT);
        cell.setCellValue(skillArrayBase[3].replaceAll("<br>", "").replaceAll("\\{", "\\{"));
    }

}

From source file:ro.dabuno.office.integration.Data.java

private void readExcelFile(File excelFile)
        throws EncryptedDocumentException, InvalidFormatException, IOException {
    try (Workbook wb = WorkbookFactory.create(excelFile, null, true)) {
        Sheet sheet = wb.getSheetAt(0);/*from   ww  w .jav  a2s . c  o m*/
        if (sheet == null) {
            throw new IllegalArgumentException(
                    "Provided Microsoft Excel file " + excelFile + " does not have any sheet");
        }

        final int start;
        final int end;
        { // read headers
            Row row = sheet.getRow(0);
            if (row == null) {
                throw new IllegalArgumentException("Provided Microsoft Excel file " + excelFile
                        + " does not have data in the first row in the first sheet, "
                        + "but we expect the header data to be located there");
            }

            start = row.getFirstCellNum();
            end = row.getLastCellNum();
            for (int cellnum = start; cellnum <= end; cellnum++) {
                Cell cell = row.getCell(cellnum);
                if (cell == null) {
                    // add null to the headers if there are columns without title in the sheet
                    headers.add(null);
                    log.info("Had empty header for column " + CellReference.convertNumToColString(cellnum));
                } else {
                    String value = cell.toString();
                    headers.add(value);
                    log.info("Had header '" + value + "' for column "
                            + CellReference.convertNumToColString(cellnum));
                }
            }
        }

        for (int rownum = 1; rownum <= sheet.getLastRowNum(); rownum++) {
            Row row = sheet.getRow(rownum);
            if (row == null) {
                // ignore missing rows
                continue;
            }

            List<String> data = new ArrayList<>();
            for (int colnum = start; colnum <= end; colnum++) {
                Cell cell = row.getCell(colnum);
                if (cell == null) {
                    // store null-data for empty/missing cells
                    data.add(null);
                } else {
                    final String value;
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_NUMERIC:
                        // ensure that numeric are formatted the same way as in the Excel file.
                        value = CellFormat.getInstance(cell.getCellStyle().getDataFormatString())
                                .apply(cell).text;
                        break;
                    default:
                        // all others can use the default value from toString() for now.
                        value = cell.toString();
                    }

                    data.add(value);
                }
            }

            values.add(data);
        }
    }
}

From source file:ru.icc.cells.ssdc.DataLoader.java

License:Apache License

private void fillCell(CCell cell, Cell excelCell) {
    String rawTextualContent = null;
    CellType cellType = null;//from   ww w  .j  a v  a2 s. co m

    String text = null;
    if (withoutSuperscript) {
        if (hasSuperscriptText(excelCell)) {
            text = getNotSuperscriptText(excelCell);
        } else {
            text = getText(excelCell);
        }
    } else {
        text = getText(excelCell);
    }
    cell.setText(text);

    rawTextualContent = getFormatCellValue(excelCell);
    cell.setRawText(rawTextualContent);

    switch (excelCell.getCellType()) {
    case Cell.CELL_TYPE_NUMERIC:
        if (DateUtil.isCellDateFormatted(excelCell)) {
            //rawTextualContent = "DATE"; // TODO - ? 
            cellType = CellType.DATE;
        } else {
            cellType = CellType.NUMERIC;
        }
        break;

    case Cell.CELL_TYPE_STRING:
        cellType = CellType.STRING;
        break;

    case Cell.CELL_TYPE_BOOLEAN:
        cellType = CellType.BOOLEAN;
        break;

    case Cell.CELL_TYPE_FORMULA:
        cellType = CellType.FORMULA;
        break;

    case Cell.CELL_TYPE_BLANK:
        cellType = CellType.BLANK;
        break;

    case Cell.CELL_TYPE_ERROR:
        cellType = CellType.ERROR;
        break;
    }

    cell.setId(this.cellCount);

    cell.setCellType(cellType);

    int height = excelCell.getRow().getHeight();
    cell.setHeight(height);

    int width = excelCell.getSheet().getColumnWidth(excelCell.getColumnIndex());
    cell.setWidth(width);

    CellStyle excelCellStyle = excelCell.getCellStyle();
    CStyle cellStyle = cell.getStyle();
    fillCellStyle(cellStyle, excelCellStyle);

    String reference = new CellReference(excelCell).formatAsString();
    cell.setProvenance(reference);

    this.cellCount++;
}

From source file:ru.spb.nicetu.tableviewer.server.XlsToHtml.java

License:Apache License

public void printStyles() {
    ensureOut();/*  w w  w.j a  v a2 s.c  om*/

    // First, copy the base css
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(rootPath + "/excelStyle.css")));
        String line;
        while ((line = in.readLine()) != null) {
            out.format("%s%n", line);
        }
    } catch (IOException e) {
        throw new IllegalStateException("Reading standard css", e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                //noinspection ThrowFromFinallyBlock
                throw new IllegalStateException("Reading standard css", e);
            }
        }
    }

    // now add css for each used style
    Set<CellStyle> seen = new HashSet<CellStyle>();
    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        Sheet sheet = wb.getSheetAt(i);
        Iterator<Row> rows = sheet.rowIterator();
        while (rows.hasNext()) {
            Row row = rows.next();
            for (Cell cell : row) {
                CellStyle style = cell.getCellStyle();
                if (!seen.contains(style)) {
                    printStyle(style, out, false, false);
                    seen.add(style);
                }
            }
        }
    }
}

From source file:ru.spb.nicetu.tableviewer.server.XlsToHtml.java

License:Apache License

private void printSheetContent(Sheet sheet) {
    printColumnHeads();/*from ww  w . j a  v a 2 s . com*/

    out.format("<tbody>%n");
    Iterator<Row> rows = sheet.rowIterator();
    int lastNum = -1;
    while (rows.hasNext()) {
        Row row = rows.next();
        int curNum = row.getRowNum();
        if (curNum - lastNum > 1) {
            for (int i = lastNum + 2; i <= curNum; i++) {
                out.format("  <tr>%n");
                out.format("    <td class=%s>%d</td>%n", ROW_HEAD_CLASS, i);
                out.format("    <td colspan=%d style=\"%s\">&nbsp;</td>%n", (endColumn - firstColumn + 1),
                        styleSimpleContents(null, false));
                out.format("  </tr>%n");
            }
        }
        lastNum = curNum;

        out.format("  <tr>%n");
        out.format("    <td class=%s>%d</td>%n", ROW_HEAD_CLASS, row.getRowNum() + 1);
        for (int i = firstColumn; i < endColumn; i++) {
            String content = "&nbsp;";
            String attrs = "";
            CellStyle style = null;
            boolean isNumeric = false;
            if (i >= row.getFirstCellNum() && i < row.getLastCellNum()) {
                Cell cell = row.getCell(i);
                if (cell != null) {
                    style = cell.getCellStyle();
                    attrs = tagStyle(cell, style);

                    CellFormat cf = CellFormat.getInstance(style.getDataFormatString());
                    CellFormatResult result = cf.apply(cell);
                    content = result.text;
                    if (content != null && !content.equals("")
                            && (cell.getCellType() == Cell.CELL_TYPE_NUMERIC
                                    || cell.getCellType() == Cell.CELL_TYPE_FORMULA
                                            && cell.getCachedFormulaResultType() == Cell.CELL_TYPE_NUMERIC)) {
                        if (DateUtil.isCellDateFormatted(cell)) {
                            // Date
                            if ("mmm-yy".equals(style.getDataFormatString())) {
                                SimpleDateFormat sdfRus = new SimpleDateFormat("MMM.yy");
                                content = sdfRus.format(cell.getDateCellValue());
                            } else if ("h:mm".equals(style.getDataFormatString())) {
                                SimpleDateFormat sdfRus = new SimpleDateFormat("HH:mm");
                                content = sdfRus.format(cell.getDateCellValue());
                            } else if (style.getDataFormatString() != null
                                    && style.getDataFormatString().contains("mm")) {
                                SimpleDateFormat sdfRus = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
                                content = sdfRus.format(cell.getDateCellValue());
                            } else {
                                SimpleDateFormat sdfRus = new SimpleDateFormat("dd.MM.yyyy");
                                content = sdfRus.format(cell.getDateCellValue());
                            }
                        } else {
                            // Number
                            if ("- 0".equals(content.trim()))
                                content = "&nbsp;";
                            else
                                content = "<nobr>" + content.replace(",", " ").replace(".", ",") + "</nobr>";
                            isNumeric = true;
                        }
                    }

                    if (content == null || content.equals(""))
                        content = "&nbsp;";
                }
            }

            boolean isInRangeNotFirst = false;
            for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
                CellRangeAddress rangeAddress = sheet.getMergedRegion(j);
                if (row.getRowNum() == rangeAddress.getFirstRow() && i == rangeAddress.getFirstColumn()) {
                    if (rangeAddress.getLastRow() - row.getRowNum() > 0)
                        attrs += " rowspan=" + (rangeAddress.getLastRow() - row.getRowNum() + 1);
                    if (rangeAddress.getLastColumn() - i > 0)
                        attrs += " colspan=" + (rangeAddress.getLastColumn() - i + 1);
                    break;
                } else if (row.getRowNum() >= rangeAddress.getFirstRow()
                        && row.getRowNum() <= rangeAddress.getLastRow() && i >= rangeAddress.getFirstColumn()
                        && i <= rangeAddress.getLastColumn()) {
                    isInRangeNotFirst = true;
                    break;
                }
            }

            if (!isInRangeNotFirst) {
                out.format("    <td style=\"%s\" %s>%s</td>%n", styleSimpleContents(style, isNumeric), attrs,
                        content);
            }
        } // columns
        out.format("  </tr>%n");
    } // rows

    out.format("</tbody>%n");
}

From source file:sol.neptune.elisaboard.service.VPlanToHtml.java

License:Apache License

public void printStyles() {
    ensureOut();// ww  w.  j  av a2  s.  com

    // First, copy the base css
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(ToHtml.class.getResourceAsStream("excelStyle.css")));
        String line;
        while ((line = in.readLine()) != null) {
            out.format("%s%n", line);
        }
    } catch (IOException e) {
        throw new IllegalStateException("Reading standard css", e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                //noinspection ThrowFromFinallyBlock
                throw new IllegalStateException("Reading standard css", e);
            }
        }
    }

    // now add css for each used style
    Set<CellStyle> seen = new HashSet<CellStyle>();
    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        Sheet sheet = wb.getSheetAt(i);
        Iterator<Row> rows = sheet.rowIterator();
        while (rows.hasNext()) {
            Row row = rows.next();
            for (Cell cell : row) {
                CellStyle style = cell.getCellStyle();
                if (!seen.contains(style)) {
                    printStyle(style);
                    seen.add(style);
                }
            }
        }
    }
}

From source file:sol.neptune.elisaboard.service.VPlanToHtml.java

License:Apache License

private void printSheetContent(Sheet sheet) {
    /* skip column heads */
    //printColumnHeads();

    out.format("<tbody>%n");
    Iterator<Row> rows = sheet.rowIterator();
    while (rows.hasNext()) {
        Row row = rows.next();//w  w w.ja va  2  s  .c  om

        out.format("  <tr>%n");
        /* skip first col*/
        /*
         out.format("    <td class=%s>%d</td>%n", ROW_HEAD_CLASS,
         row.getRowNum() + 1);
         */
        for (int i = firstColumn; i < endColumn; i++) {
            String content = "&nbsp;";
            String attrs = "";
            CellStyle style = null;
            if (i >= row.getFirstCellNum() && i < row.getLastCellNum()) {
                Cell cell = row.getCell(i);
                if (cell != null) {
                    style = cell.getCellStyle();
                    attrs = tagStyle(cell, style);
                    //Set the value that is rendered for the cell
                    //also applies the format
                    CellFormat cf = CellFormat.getInstance(style.getDataFormatString());
                    CellFormatResult result = cf.apply(cell);
                    content = result.text;
                    if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                        final Date date = cell.getDateCellValue();
                        System.out.println("Date: " + date);
                        System.out.println(new Date());

                    }
                    if (content.equals("")) {
                        content = "&nbsp;";
                    }
                }
            }
            out.format("    <td class=%s %s>%s</td>%n", styleName(style), attrs, content);
        }
        out.format("  </tr>%n");
    }
    out.format("</tbody>%n");
}

From source file:Tools.PostProcessing.java

private void colorDeletedLeaves(String ssn, Cell ctrlNumCell, XSSFWorkbook myWorkBook,
        Map<String, Integer> statusMap) {
    String ctrlNumString = null;//from   w  w  w .  ja v a 2 s .  co  m
    if (ctrlNumCell != null && ctrlNumCell.getStringCellValue() != null) {
        ctrlNumString = ctrlNumCell.getStringCellValue().trim();
        // color valid leaves
        CellStyle style = ctrlNumCell.getCellStyle();
        String key = ssn + ctrlNumString;
        if (style.getFillForegroundColor() == IndexedColors.GREEN.getIndex()) {
            statusMap.put(key, GlobalVar.NO_ERR);
            if (!LEGIT_LV_MAP_FOR_COLOR_LV_LOG.containsKey(ssn)) { // Map< SSN, Map<ctrlNum, signOutdate>>
                style.setFillForegroundColor(GlobalVar.AUDITOR_DELETED_COLOR);
                style.setFillPattern(CellStyle.SOLID_FOREGROUND);
                ctrlNumCell.setCellStyle(style);
                statusMap.put(key, GlobalVar.AUDIT_DELETE_ERR);
            } else { // contains SSN
                Map<String, String> list = LEGIT_LV_MAP_FOR_COLOR_LV_LOG.get(ssn);
                if (!list.keySet().contains(ctrlNumString)) {
                    style.setFillForegroundColor(GlobalVar.AUDITOR_DELETED_COLOR);
                    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
                    ctrlNumCell.setCellStyle(style);
                    statusMap.put(key, GlobalVar.AUDIT_DELETE_ERR);
                }
            }
        } else if (style.getFillForegroundColor() == GlobalVar.BAD_STATUS_COLOR) {
            statusMap.put(key, GlobalVar.BAD_STATUS_ERR);
        } else if (style.getFillForegroundColor() == GlobalVar.ETS_STATUS_COLOR) {
            statusMap.put(key, GlobalVar.ETS_ERR);
        } else if (style.getFillForegroundColor() == GlobalVar.DUPLICATE_LV_COLOR) {
            statusMap.put(key, GlobalVar.DUPLICATE_LV_ERR);
        } else if (style.getFillForegroundColor() == GlobalVar.DUPLICATE_CTRL_NUM_COLOR) {
            statusMap.put(key, GlobalVar.DUPLICATE_CTRL_NUM_ERR);
        } else if (style.getFillForegroundColor() == GlobalVar.AFTER_PCS_COLOR) {
            statusMap.put(key, GlobalVar.AFTER_PCS_ERR);
        } else if (style.getFillForegroundColor() == GlobalVar.INPROCESSING_COLOR) {
            statusMap.put(key, GlobalVar.INPROCESSING_ERR);
        } else if (style.getFillForegroundColor() == GlobalVar.WRONG_SSN_COLOR) {
            statusMap.put(key, GlobalVar.WRONG_SSN_ERR);
        } else if (style.getFillForegroundColor() == GlobalVar.OVERLAP_LV_COLOR) {
            statusMap.put(key, GlobalVar.OVERLAP_LV_ERR);
        } else if (style.getFillForegroundColor() == GlobalVar.AUDITOR_DELETED_COLOR) {
            statusMap.put(key, GlobalVar.AUDIT_DELETE_ERR);
        } else {
            statusMap.put(key, GlobalVar.IN_CYCLE_DUPLICATION_INVALID_FIRST_FIVE_ERR);
        }
    }
}

From source file:uk.ac.liverpool.spreadsheet.ExcelFeatureAnalysis.java

License:Apache License

private static void analyseSheet(Sheet ss, Element s, Namespace n, ExcelFeatureAnalysis efa) {
    // generic part
    boolean costumFormatting = false;
    boolean formulae = false;
    boolean UDF = false;
    boolean hasComments = false;

    Set<String> udfs = new HashSet<String>();
    FormulaEvaluator evaluator = ss.getWorkbook().getCreationHelper().createFormulaEvaluator();

    s.setAttribute("name", ss.getSheetName());
    s.setAttribute("firstRow", "" + ss.getFirstRowNum());
    s.setAttribute("lastRow", "" + ss.getLastRowNum());
    try {//from  w ww  .  j a  v  a  2s . c  om
        s.setAttribute("forceFormulaRecalc", "" + ss.getForceFormulaRecalculation());
    } catch (Throwable x) {
        //x.printStackTrace();
    }

    // shapes in detail? 
    Footer footer = ss.getFooter();
    if (footer != null) {
        s.setAttribute("footer", "true");
    }
    Header header = ss.getHeader();
    if (header != null) {
        s.setAttribute("header", "true");
    }
    PaneInformation paneInformation = ss.getPaneInformation();
    if (paneInformation != null) {
        s.setAttribute("panels", "true");
    }

    HSSFSheet hs = null;
    XSSFSheet xs = null;
    if (ss instanceof HSSFSheet) {
        hs = (HSSFSheet) ss;
        try {
            if (hs.getDrawingPatriarch() != null) {
                if (hs.getDrawingPatriarch().containsChart())
                    s.addContent(new Element("charts", sn));
                if (hs.getDrawingPatriarch().countOfAllChildren() > 0)
                    s.addContent(new Element("shapes", sn));
            }
        } catch (Exception x) {
            x.printStackTrace();
        }

        if (hs.getSheetConditionalFormatting().getNumConditionalFormattings() > 0) {
            s.setAttribute("conditionalFormatting", "true");
        }
    }
    if (ss instanceof XSSFSheet) {
        xs = (XSSFSheet) ss;

    }
    Iterator<Row> rows = ss.rowIterator();

    int firstColumn = (rows.hasNext() ? Integer.MAX_VALUE : 0);
    int endColumn = 0;
    while (rows.hasNext()) {
        Row row = rows.next();
        short firstCell = row.getFirstCellNum();
        if (firstCell >= 0) {
            firstColumn = Math.min(firstColumn, firstCell);
            endColumn = Math.max(endColumn, row.getLastCellNum());
        }
    }
    s.setAttribute("firstColumn", "" + firstColumn);
    s.setAttribute("lastColumn", "" + endColumn);
    rows = ss.rowIterator();
    while (rows.hasNext()) {
        Row row = rows.next();
        for (Cell cell : row)
            if (cell != null) {
                try {
                    if (!cell.getCellStyle().getDataFormatString().equals("GENERAL"))
                        costumFormatting = true;
                } catch (Throwable t) {
                }

                if (cell.getCellComment() != null)
                    hasComments = true;
                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    // System.out.println(cell.getRichStringCellValue().getString());
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    //                        if (DateUtil.isCellDateFormatted(cell)) {
                    //                            // System.out.println(cell.getDateCellValue());
                    //                        } else {
                    //                            // System.out.println(cell.getNumericCellValue());
                    //                        }
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    // System.out.println(cell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    // System.out.println(cell.getCellFormula());
                    formulae = true;
                    if (!UDF)
                        try {
                            evaluator.evaluate(cell);
                        } catch (Exception x) {
                            if (x instanceof NotImplementedException) {
                                Throwable e = x;

                                //e.printStackTrace();
                                while (e != null) {
                                    for (StackTraceElement c : e.getStackTrace()) {
                                        if (c.getClassName().contains("UserDefinedFunction")) {
                                            UDF = true;
                                            System.out.println("UDF " + e.getMessage());
                                            udfs.add(e.getMessage());
                                        }
                                    }
                                    e = e.getCause();
                                }

                            }
                        }
                    break;
                default:
                }

            }
    }
    if (costumFormatting) {
        Element cf = new Element("customisedFormatting", sn);
        s.addContent(cf);
    }
    if (formulae) {
        Element cf = new Element("formulae", sn);
        s.addContent(cf);
    }
    if (UDF) {
        Element cf = new Element("userDefinedFunctions", sn);
        for (String sss : udfs)
            cf.addContent(new Element("userDefinedFunction", sn).setAttribute("functionName", sss));
        s.addContent(cf);
    }
    if (hasComments) {
        Element cf = new Element("cellComments", sn);
        s.addContent(cf);
    }
}