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

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

Introduction

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

Prototype

void setCellFormula(String formula) throws FormulaParseException, IllegalStateException;

Source Link

Document

Sets formula for this cell.

Usage

From source file:de.enerko.reports2.engine.Report.java

License:Apache License

private Cell fill(final Workbook workbook, Cell tmp, final CellDefinition cellDefinition, boolean setType) {
    final String type = cellDefinition.getType();

    if (type.equalsIgnoreCase("string")) {
        if (setType)
            tmp.setCellType(Cell.CELL_TYPE_STRING);
        tmp.setCellValue(cellDefinition.value);
    } else if (type.equalsIgnoreCase("number")) {
        if (setType) {
            tmp.setCellType(Cell.CELL_TYPE_NUMERIC);
            tmp.setCellStyle(getFormat(workbook, tmp, type, cellDefinition.value));
        }//from  w  w w. ja  v  a  2s.  co  m
        try {
            tmp.setCellValue(Double.parseDouble(cellDefinition.value.split("@@")[0]));
        } catch (NumberFormatException e) {
            throw new RuntimeException(String.format("Could not parse value \"%s\" for numeric cell %dx%d!",
                    cellDefinition.value, tmp.getColumnIndex(), tmp.getRowIndex()));
        }
    } else if (type.equalsIgnoreCase("date") || type.equalsIgnoreCase("datetime")) {
        if (setType) {
            tmp.setCellType(Cell.CELL_TYPE_NUMERIC);
            tmp.setCellStyle(getFormat(workbook, tmp, type, cellDefinition.value));
        }
        try {
            tmp.setCellValue(getDateFormatSql(type).parse(cellDefinition.value));
        } catch (ParseException e) {
            throw new RuntimeException(
                    String.format("Could not parse value \"%s\" for date/datetime cell %dx%d!",
                            cellDefinition.value, tmp.getColumnIndex(), tmp.getRowIndex()));
        }
    } else if (type.equalsIgnoreCase("formula")) {
        if (setType)
            tmp.setCellType(Cell.CELL_TYPE_FORMULA);
        tmp.setCellFormula(cellDefinition.value);
    } else
        throw new RuntimeException("Invalid type " + type);
    return tmp;
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticExcel.util.ExcelGeneratorUtils.java

License:Open Source License

/**
 * Adds formulas to the <i>full parent name</i> column on the current sheet, which derives the fully hierarchical parent name from the
 * non-hierarchical name./*  w  w w .  j  a v  a2  s.  c o m*/
 * @param wbContext
 *        The Context for the currently generated workbook. Used to extract cell style information.
 * @param sheetContext
 *        The Context for the relationship sheet that should be operated upon.
 * @param dataSetSize
 *        The number of rows to be formatted with dropdowns
 */
public static void addFullParentNameFormula(WorkbookContext wbContext, SheetContext sheetContext,
        int dataSetSize) {
    short fullParentNameColumnNumber = sheetContext.getColumnFullParentNameColumnNumber();

    if (fullParentNameColumnNumber < 0) {
        // there is no full parent name column --> abort!
        return;
    }

    ColumnContext nameColumn = sheetContext.getColumnByPersistentName(SheetContext.NAME_COLUMN);
    ColumnContext parentColumn = sheetContext.getColumnByPersistentName(SheetContext.PARENT_COLUMN);
    int firstDataRow = sheetContext.getFirstDataRowNumber();
    int lastDataRow = sheetContext.calculateLastDataRow(dataSetSize);

    CellRangeAddress matrix = new CellRangeAddress(firstDataRow, lastDataRow, nameColumn.getColumnNumber(),
            fullParentNameColumnNumber);
    // for each cell in column, set lookup formula and cell style
    for (int rowIndex = firstDataRow; rowIndex <= lastDataRow; rowIndex++) {
        Row row = ExcelUtils.getOrCreateRow(sheetContext.getSheet(), rowIndex);
        Cell fullParentNameCell = ExcelUtils.getOrCreateCell(row, fullParentNameColumnNumber);
        fullParentNameCell.setCellStyle(wbContext.getStyles().get(IteraExcelStyle.DATA_HIDDEN));
        String lookupFormula = createLookupFormula(parentColumn.getColumnName(), nameColumn.getColumnName(),
                rowIndex + 1, matrix, sheetContext.getSheetName());
        fullParentNameCell.setCellFormula(lookupFormula);
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.exporter.ExportWorkbook.java

License:Open Source License

/**
 * Sets given value and style of the given cell and adds the given <code>link</code> as hyperlink
 * to the <code>cell</code>.
 * /*from  w w  w .ja va2s . c om*/
 * @param cell
 *          the cell in question
 * @param value
 *          the value to be set
 * @param link
 *          the link to be added
 * @param style
 *          if <code>null</code> the default style for hyperlinks is taken
 */
private void setHyperlink(Cell cell, Integer value, Hyperlink link, CellStyle style) {
    if (cell == null) {
        return;
    }
    if ((value != null) && (link != null)) {
        cell.setCellFormula("HYPERLINK(\"" + link.getAddress() + "\"," + value + ")");
    }

    CellStyle styleToSet = (style != null ? style : getHyperlinkStyle());
    cell.setCellStyle(styleToSet);
}

From source file:de.jlo.talendcomp.excel.SpreadsheetOutput.java

License:Apache License

private void writeCellValue(Cell cell, Object value, int dataColumnIndex, int dataRowIndex) {
    if (value instanceof String) {
        String s = (String) value;
        boolean isPlainValue = true;
        if (isToWriteAsComment(dataColumnIndex)) {
            // if this schema data column is dedicated as comment 
            isPlainValue = false;//from  w w  w  .j ava2s . c om
            if (firstRowIsHeader == false || dataRowIndex > 0) {
                // avoid set comment for the header line
                setCellComment(cell, s);
            }
        }
        if (isToWriteAsLink(dataColumnIndex)) {
            // if this schema data column is dedicated as hyper link
            if (firstRowIsHeader == false || dataRowIndex > 0) {
                // avoid set hyper-links for the header line
                setCellHyperLink(cell, s);
                isPlainValue = false;
            }
        }
        if (isPlainValue) {
            if (s.startsWith("=")) {
                int rowNum = cell.getRow().getRowNum();
                cell.setCellFormula(getFormular(s, rowNum));
                cell.setCellType(CellType.FORMULA);
            } else {
                cell.setCellValue(s);
                cell.setCellType(CellType.STRING);
            }
        }
    } else if (value instanceof Integer) {
        cell.setCellValue((Integer) value);
        cell.setCellType(CellType.NUMERIC);
    } else if (value instanceof Boolean) {
        cell.setCellValue((Boolean) value);
        cell.setCellType(CellType.BOOLEAN);
    } else if (value instanceof Long) {
        cell.setCellValue((Long) value);
        cell.setCellType(CellType.NUMERIC);
    } else if (value instanceof BigInteger) {
        cell.setCellValue(((BigInteger) value).longValue());
        cell.setCellType(CellType.NUMERIC);
    } else if (value instanceof BigDecimal) {
        cell.setCellValue(((BigDecimal) value).doubleValue());
        cell.setCellType(CellType.NUMERIC);
    } else if (value instanceof Double) {
        cell.setCellValue((Double) value);
        cell.setCellType(CellType.NUMERIC);
    } else if (value instanceof Float) {
        cell.setCellValue((Float) value);
        cell.setCellType(CellType.NUMERIC);
    } else if (value instanceof Short) {
        cell.setCellValue((Short) value);
        cell.setCellType(CellType.NUMERIC);
    } else if (value instanceof Number) {
        cell.setCellValue(Double.valueOf(((Number) value).doubleValue()));
        cell.setCellType(CellType.NUMERIC);
    } else if (value instanceof Date) {
        if (writeZeroDateAsNull && GenericDateUtil.isZeroDate((Date) value)) {
            cell.setCellType(CellType.BLANK);
        } else {
            cell.setCellValue((Date) value);
            cell.setCellType(CellType.NUMERIC);
        }
    } else if (value != null) {
        cell.setCellValue(value.toString());
        cell.setCellType(CellType.STRING);
    } else if (writeNullValues && value == null) {
        cell.setCellType(CellType.BLANK);
    }
    if (isDataRow(dataRowIndex)) {
        setupStyle(cell, dataRowIndex);
    }
}

From source file:de.thb.ue.backend.util.EvaluationExcelFileGenerator.java

License:Apache License

public void generateExcelFile() {

    Row row;/*from www  . java  2s . c  o  m*/
    Cell cell;
    int yOffset = 1;
    File workingDirectory = new File(
            (workingDirectoryPath.isEmpty() ? "" : (workingDirectoryPath + File.separatorChar))
                    + evaluationUID);
    if (!workingDirectory.exists()) {
        workingDirectory.mkdir();
    }
    File file = new File(workingDirectory, "auswertung.xls");

    try {
        FileOutputStream out = new FileOutputStream(file);
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("Evaluation");

        // configure cell styles
        configureCellStyles(wb);

        /*
        * **********************************
        * begin formatting document
        * **********************************
        * */

        //construct first row of infopanel
        yOffset = constructInfoPanelRow("Lehrveranstaltung", subject, numberStudentsAll, yOffset, wb, sheet,
                InfoPanelBorderStyles.topLeftCorner, InfoPanelBorderStyles.top,
                InfoPanelBorderStyles.topRightCorner);

        //construct second row of infopanel
        yOffset = constructInfoPanelRow("Semester", semesterType == SemesterType.WINTER ? "Winter" : "Sommer",
                numberStudentsAll, yOffset, wb, sheet, InfoPanelBorderStyles.left, InfoPanelBorderStyles.none,
                InfoPanelBorderStyles.right);

        //construct third row of infopanel
        StringBuilder tutors = new StringBuilder();
        for (int i = 0; i < this.tutors.size(); i++) {
            if (i + 1 < this.tutors.size()) {
                tutors.append(this.tutors.get(i)).append(", ");
            } else {
                tutors.append(this.tutors.get(i));
            }
        }

        yOffset = constructInfoPanelRow("Lehrende(r)", tutors.toString(), numberStudentsAll, yOffset, wb, sheet,
                InfoPanelBorderStyles.left, InfoPanelBorderStyles.none, InfoPanelBorderStyles.right);

        //construct fourth row of infopanel
        yOffset = constructInfoPanelRow("Datum der Befragung", dateOfEvaluation.toString("dd.MM.yy HH:mm"),
                numberStudentsAll, yOffset, wb, sheet, InfoPanelBorderStyles.left, InfoPanelBorderStyles.none,
                InfoPanelBorderStyles.right);

        //construct fifth row of infopanel
        yOffset = constructInfoPanelRow("Anzahl der Teilnehmer", Integer.toString(numberStudentsAll),
                numberStudentsAll, yOffset, wb, sheet, InfoPanelBorderStyles.left, InfoPanelBorderStyles.none,
                InfoPanelBorderStyles.right);

        //construct sixth row of infopanel () last
        yOffset = constructInfoPanelRow("Anzahl der ausgefllten Fragebgen",
                Integer.toString(numberStudentsVoted), numberStudentsAll, yOffset, wb, sheet,
                InfoPanelBorderStyles.bottomLeftCorner, InfoPanelBorderStyles.bottom,
                InfoPanelBorderStyles.bottomRightCorner);

        //begin construction of evaluationPanel
        yOffset++;
        row = sheet.createRow(yOffset);
        cell = row.createCell(1, Cell.CELL_TYPE_STRING);
        cell.setCellValue("Frage");
        cell.setCellStyle(headerStyle);

        cell = row.createCell(2, Cell.CELL_TYPE_STRING);
        cell.setCellValue("MW");
        cell.setCellStyle(headerStyle);

        cell = row.createCell(3, Cell.CELL_TYPE_STRING);
        cell.setCellValue("Ifd NR.");
        cell.setCellStyle(headerStyle);

        cell = row.createCell(4);
        cell.setCellStyle(commonStyle);

        // add count of valid evaluations (how many students voted) (horizontal)
        for (int i = 0; i < numberStudentsVoted; i++) {
            cell = row.createCell(i + 5);
            cell.setCellValue(i + 1);
            sheet.setColumnWidth(cell.getColumnIndex(), 4 * 256);
            cell.setCellStyle(headerStyle);
        }

        // get letter of last student column
        CellReference cellReference = new CellReference(cell.getRowIndex(), cell.getColumnIndex());
        String endCellName = cellReference.getCellRefParts()[2];

        Row headRow = row;

        for (int i = 1; i < mcQuestionTexts.size() + 1; i++) {
            //add number of questions
            row = sheet.createRow(i + yOffset);
            cell = row.createCell(1, Cell.CELL_TYPE_NUMERIC);
            cell.setCellValue(i);
            cell.setCellStyle(commonStyle);

            //add average formula
            cell = row.createCell(2, Cell.CELL_TYPE_FORMULA);
            //formlua works with blanks, empty strings and negative values
            String formula = "SUMPRODUCT(ABS(N(+F" + (i + yOffset + 1) + ":" + endCellName + (i + yOffset + 1)
                    + ")))/COUNT(F" + (i + yOffset + 1) + ":" + endCellName + (i + yOffset + 1) + ")";
            //String averageFormula = "AVERAGE(IF(F" + (i + yOffset + 1) + ":" + endCellName + (i + yOffset + 1) + "<>\"\", ABS(F" + (i + yOffset + 1) + ":" + endCellName + (i + yOffset + 1) + ")))";
            cell.setCellFormula(formula);
            cell.setCellStyle(commonStyle);

            //fill blank cells
            cell = row.createCell(3);
            cell.setCellStyle(commonStyle);

            //add question texts
            sheet.setColumnWidth(4, findLongestString(mcQuestionTexts) * 256
                    * (wb.getFontAt(questionStyle.getFontIndex()).getFontHeightInPoints()) / 10);
            cell = row.createCell(4, Cell.CELL_TYPE_STRING);
            cell.setCellValue(mcQuestionTexts.get(i - 1));
            cell.setCellStyle(questionStyle);
        }

        //add student votes
        for (int i = 0; i < studentVotes.size(); i++) {
            Vote vote = studentVotes.get(i);
            for (int k = 0; k < mcQuestionTexts.size(); k++) {
                row = sheet.getRow(headRow.getRowNum() + 1 + k);
                cell = row.createCell(5 + i);
                for (MCAnswer answer : vote.getMcAnswers()) {
                    //if question of inner loop equals question of outer loop we found
                    // the correct question for this cell
                    if (answer.getQuestion().getText().equals(mcQuestionTexts.get(k))) {
                        Choice choice = answer.getChoice();
                        if (choice != null && choice.getGrade() != 0) {
                            cell = colorizeCell(cell, wb, choice.getGrade());
                            cell.setCellValue(answer.getChoice().getGrade());
                        } else {
                            cell = colorizeCell(cell, wb, -1);
                            cell.setCellValue("");
                        }
                    }
                }
            }
        }

        // include textual answers
        createTextualAnswers(studentVotes, textualQuestionTexts, sheet, wb);
        wb.write(out);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:demo.poi.BusinessPlan.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb = new HSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);

    Sheet sheet = wb.createSheet("Business Plan");

    // turn off gridlines
    sheet.setDisplayGridlines(false);/*w  w w . j av  a  2s .  c  o  m*/
    sheet.setPrintGridlines(false);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);

    // the following three statements are required only for HSSF
    sheet.setAutobreaks(true);
    printSetup.setFitHeight((short) 1);
    printSetup.setFitWidth((short) 1);

    // the header row: centered text in 48pt font
    Row headerRow = sheet.createRow(0);
    headerRow.setHeightInPoints(12.75f);
    for (int i = 0; i < titles.length; i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellValue(titles[i]);
        cell.setCellStyle(styles.get("header"));
    }
    // columns for 11 weeks starting from 9-Jul
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);

    calendar.setTime(fmt.parse("9-Jul"));
    calendar.set(Calendar.YEAR, year);
    for (int i = 0; i < 11; i++) {
        Cell cell = headerRow.createCell(titles.length + i);
        cell.setCellValue(calendar);
        cell.setCellStyle(styles.get("header_date"));
        calendar.roll(Calendar.WEEK_OF_YEAR, true);
    }
    // freeze the first row
    sheet.createFreezePane(0, 1);

    Row row;
    Cell cell;
    int rownum = 1;
    for (int i = 0; i < data.length; i++, rownum++) {
        row = sheet.createRow(rownum);
        if (data[i] == null)
            continue;

        for (int j = 0; j < data[i].length; j++) {
            String str = data[i][j];
            cell = row.createCell(j);
            String styleName;
            boolean isHeader = i == 0 || data[i - 1] == null;
            switch (j) {
            case 0:
                if (isHeader) {
                    styleName = "cell_b";
                    cell.setCellValue(Double.parseDouble(data[i][j]));
                } else {
                    styleName = "cell_normal";
                    cell.setCellValue(data[i][j]);
                }
                break;
            case 1:
                if (isHeader) {
                    styleName = i == 0 ? "cell_h" : "cell_bb";
                } else {
                    styleName = "cell_indented";
                }
                cell.setCellValue(data[i][j]);
                break;
            case 2:
                styleName = isHeader ? "cell_b" : "cell_normal";
                cell.setCellValue(data[i][j]);
                break;
            case 3:
                styleName = isHeader ? "cell_b_centered" : "cell_normal_centered";
                cell.setCellValue(Integer.parseInt(data[i][j]));
                break;
            case 4: {
                calendar.setTime(fmt.parse(data[i][j]));
                calendar.set(Calendar.YEAR, year);
                cell.setCellValue(calendar);
                styleName = isHeader ? "cell_b_date" : "cell_normal_date";
                break;
            }
            case 5: {
                int r = rownum + 1;
                String fmla = "IF(AND(D" + r + ",E" + r + "),E" + r + "+D" + r + ",\"\")";
                cell.setCellFormula(fmla);
                styleName = isHeader ? "cell_bg" : "cell_g";
                break;
            }
            default:
                styleName = data[i][j] != null ? "cell_blue" : "cell_normal";
            }

            cell.setCellStyle(styles.get(styleName));
        }
    }

    // group rows for each phase, row numbers are 0-based
    sheet.groupRow(4, 6);
    sheet.groupRow(9, 13);
    sheet.groupRow(16, 18);

    // set column widths, the width is measured in units of 1/256th of a
    // character width
    sheet.setColumnWidth(0, 256 * 6);
    sheet.setColumnWidth(1, 256 * 33);
    sheet.setColumnWidth(2, 256 * 20);
    sheet.setZoom(3, 4);

    // Write the output to a file
    String file = "target/businessplan.xls";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:demo.poi.LoanCalculator.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb;/*from w  w w .  j av a2  s  .  c  o  m*/

    if (args.length > 0 && args[0].equals("-xls"))
        wb = new HSSFWorkbook();
    else
        wb = new HSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);
    Sheet sheet = wb.createSheet("Loan Calculator");
    sheet.setPrintGridlines(false);
    sheet.setDisplayGridlines(false);

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);

    sheet.setColumnWidth(0, 3 * 256);
    sheet.setColumnWidth(1, 3 * 256);
    sheet.setColumnWidth(2, 11 * 256);
    sheet.setColumnWidth(3, 14 * 256);
    sheet.setColumnWidth(4, 14 * 256);
    sheet.setColumnWidth(5, 14 * 256);
    sheet.setColumnWidth(6, 14 * 256);

    createNames(wb);

    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(35);
    for (int i = 1; i <= 7; i++) {
        titleRow.createCell(i).setCellStyle(styles.get("title"));
    }
    Cell titleCell = titleRow.getCell(2);
    titleCell.setCellValue("Simple Loan Calculator");
    sheet.addMergedRegion(CellRangeAddress.valueOf("$C$1:$H$1"));

    Row row = sheet.createRow(2);
    Cell cell = row.createCell(4);
    cell.setCellValue("Enter values");
    cell.setCellStyle(styles.get("item_right"));

    row = sheet.createRow(3);
    cell = row.createCell(2);
    cell.setCellValue("Loan amount");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_$"));
    cell.setAsActiveCell();

    row = sheet.createRow(4);
    cell = row.createCell(2);
    cell.setCellValue("Annual interest rate");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_%"));

    row = sheet.createRow(5);
    cell = row.createCell(2);
    cell.setCellValue("Loan period in years");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_i"));

    row = sheet.createRow(6);
    cell = row.createCell(2);
    cell.setCellValue("Start date of loan");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellStyle(styles.get("input_d"));

    row = sheet.createRow(8);
    cell = row.createCell(2);
    cell.setCellValue("Monthly payment");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Monthly_Payment,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    row = sheet.createRow(9);
    cell = row.createCell(2);
    cell.setCellValue("Number of payments");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Loan_Years*12,\"\")");
    cell.setCellStyle(styles.get("formula_i"));

    row = sheet.createRow(10);
    cell = row.createCell(2);
    cell.setCellValue("Total interest");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Total_Cost-Loan_Amount,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    row = sheet.createRow(11);
    cell = row.createCell(2);
    cell.setCellValue("Total cost of loan");
    cell.setCellStyle(styles.get("item_left"));
    cell = row.createCell(4);
    cell.setCellFormula("IF(Values_Entered,Monthly_Payment*Number_of_Payments,\"\")");
    cell.setCellStyle(styles.get("formula_$"));

    // Write the output to a file
    String file = "target/loan-calculator.xls";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:demo.poi.TimesheetDemo.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb;/*from  w  w  w  . j a  v  a2s  .co m*/

    if (args.length > 0 && args[0].equals("-xls"))
        wb = new HSSFWorkbook();
    else
        wb = new HSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);

    Sheet sheet = wb.createSheet("Timesheet");
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);

    // title row
    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(45);
    Cell titleCell = titleRow.createCell(0);
    titleCell.setCellValue("Weekly Timesheet");
    titleCell.setCellStyle(styles.get("title"));
    sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$L$1"));

    // header row
    Row headerRow = sheet.createRow(1);
    headerRow.setHeightInPoints(40);
    Cell headerCell;
    for (int i = 0; i < titles.length; i++) {
        headerCell = headerRow.createCell(i);
        headerCell.setCellValue(titles[i]);
        headerCell.setCellStyle(styles.get("header"));
    }

    int rownum = 2;
    for (int i = 0; i < 10; i++) {
        Row row = sheet.createRow(rownum++);
        for (int j = 0; j < titles.length; j++) {
            Cell cell = row.createCell(j);
            if (j == 9) {
                // the 10th cell contains sum over week days, e.g.
                // SUM(C3:I3)
                String ref = "C" + rownum + ":I" + rownum;
                cell.setCellFormula("SUM(" + ref + ")");
                cell.setCellStyle(styles.get("formula"));
            } else if (j == 11) {
                cell.setCellFormula("J" + rownum + "-K" + rownum);
                cell.setCellStyle(styles.get("formula"));
            } else {
                cell.setCellStyle(styles.get("cell"));
            }
        }
    }

    // row with totals below
    Row sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(35);
    Cell cell;
    cell = sumRow.createCell(0);
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellValue("Total Hrs:");
    cell.setCellStyle(styles.get("formula"));

    for (int j = 2; j < 12; j++) {
        cell = sumRow.createCell(j);
        String ref = (char) ('A' + j) + "3:" + (char) ('A' + j) + "12";
        cell.setCellFormula("SUM(" + ref + ")");
        if (j >= 9)
            cell.setCellStyle(styles.get("formula_2"));
        else
            cell.setCellStyle(styles.get("formula"));
    }
    rownum++;
    sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(25);
    cell = sumRow.createCell(0);
    cell.setCellValue("Total Regular Hours");
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellFormula("L13");
    cell.setCellStyle(styles.get("formula_2"));
    sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(25);
    cell = sumRow.createCell(0);
    cell.setCellValue("Total Overtime Hours");
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellFormula("K13");
    cell.setCellStyle(styles.get("formula_2"));

    // set sample data
    for (int i = 0; i < sample_data.length; i++) {
        Row row = sheet.getRow(2 + i);
        for (int j = 0; j < sample_data[i].length; j++) {
            if (sample_data[i][j] == null)
                continue;

            if (sample_data[i][j] instanceof String) {
                row.getCell(j).setCellValue((String) sample_data[i][j]);
            } else {
                row.getCell(j).setCellValue((Double) sample_data[i][j]);
            }
        }
    }

    // finally set column widths, the width is measured in units of 1/256th
    // of a character width
    sheet.setColumnWidth(0, 30 * 256); // 30 characters wide
    for (int i = 2; i < 9; i++) {
        sheet.setColumnWidth(i, 6 * 256); // 6 characters wide
    }
    sheet.setColumnWidth(10, 10 * 256); // 10 characters wide

    // Write the output to a file
    String file = "target/timesheet.xls";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}

From source file:dk.cubing.liveresults.action.admin.ScoresheetAction.java

License:Open Source License

/**
 * @param workBook//from   ww  w  .ja  va 2  s . c  o m
 * @param sheet
 * @param competitors
 * @param startrow
 */
private void generateCompetitorRows(Workbook workBook, Sheet sheet, List<Competitor> competitors,
        int startrow) {
    int line = startrow;
    for (Competitor competitor : competitors) {
        // number
        if (SHEET_TYPE_REGISTRATION.equals(sheet.getSheetName())) {
            Cell number = getCell(sheet, line, 0, Cell.CELL_TYPE_FORMULA);
            number.setCellFormula("IF(COUNTBLANK(B" + line + ")>0,\"\",ROW()-3)");
        }

        // name
        Cell name = getCell(sheet, line, 1, Cell.CELL_TYPE_STRING);
        name.setCellValue(competitor.getFirstname() + " " + competitor.getSurname());

        // country
        Cell country = getCell(sheet, line, 2, Cell.CELL_TYPE_STRING);
        country.setCellValue(countryUtil.getCountryByCode(competitor.getCountry()));

        // wca id
        String wcaId = competitor.getWcaId();
        Cell wcaIdCell = null;
        if (wcaId == null || "".equals(wcaId)) {
            wcaIdCell = getCell(sheet, line, 3, Cell.CELL_TYPE_BLANK);
        } else {
            wcaIdCell = getCell(sheet, line, 3, Cell.CELL_TYPE_STRING);
            wcaIdCell.setCellValue(wcaId);
        }

        // handle registration sheet
        if (SHEET_TYPE_REGISTRATION.equals(sheet.getSheetName())) {
            // gender
            Cell gender = getCell(sheet, line, 4, Cell.CELL_TYPE_STRING);
            gender.setCellValue(competitor.getGender());

            // birthday
            Cell birthday = getCell(sheet, line, 5, Cell.CELL_TYPE_NUMERIC);
            birthday.setCellValue(competitor.getBirthday());

            // registered events
            List<Boolean> signupList = competitor.getRegisteredEvents().getSignupList();
            for (int i = 0; i < signupList.size(); i++) {
                if (signupList.get(i)) {
                    Cell signup = getCell(sheet, line, 7 + i, Cell.CELL_TYPE_NUMERIC);
                    signup.setCellValue(1);
                }
            }
        }

        // loop
        line++;
    }

    // adjust competitors count per event
    if (SHEET_TYPE_REGISTRATION.equals(sheet.getSheetName())) {
        for (int i = 0; i < 33; i++) {
            Cell count = getCell(sheet, 1, 7 + i, Cell.CELL_TYPE_FORMULA);
            String col = CellReference.convertNumToColString(7 + i);
            String ref = col + "4:" + col + line;
            count.setCellFormula("SUM(" + ref + ")");
        }
    }
}

From source file:dk.cubing.liveresults.action.admin.ScoresheetAction.java

License:Open Source License

/**
 * @param workBook/*from w  w w. j ava 2s . c  o  m*/
 * @param template
 * @param competition
 * @param event
 * @param round
 * @param includeCompetitors
 */
private void createResultSheetFromTemplate(Workbook workBook, Sheet template, Competition competition,
        Event event, String round, boolean includeCompetitors) {
    Sheet resultSheet = workBook.cloneSheet(workBook.getSheetIndex(template));
    String sheetName = null;
    String eventNameFormatted = null;
    if (round == null) {
        sheetName = event.getName(); // TODO: format to short sheetname
        eventNameFormatted = event.getName();
    } else {
        sheetName = event.getName() + " - " + getRoundTypesMap().get(round);
        eventNameFormatted = getText("admin.scoresheet.eventname." + event.getName().toLowerCase()) + " - "
                + getRoundTypesMap().get(round);
    }
    log.debug("Building result sheet: {}", sheetName);
    workBook.setSheetName(workBook.getSheetIndex(resultSheet), sheetName);
    workBook.setSheetOrder(sheetName, 1); // first sheet is the registration sheet, let's put results directly after that
    Cell eventName = getCell(resultSheet, 0, 0, Cell.CELL_TYPE_STRING);
    eventName.setCellValue(eventNameFormatted);

    // get cell styles from template
    List<CellStyle> cellStyles = new ArrayList<CellStyle>();
    Row startRow = template.getRow(4);
    int numberOfColumns = template.getRow(3).getPhysicalNumberOfCells();
    if (startRow != null) {
        log.debug("Start row contains {} cells.", numberOfColumns);
        for (int i = 0; i < numberOfColumns; i++) {
            Cell cell = startRow.getCell(i);
            if (cell != null) {
                cellStyles.add(cell.getCellStyle());
            } else {
                cellStyles.add(workBook.createCellStyle());
            }
        }
    }

    // adjust formulas
    int numberOfCompetitors = (round == null) ? event.getResults().size() : competition.getCompetitors().size();
    for (int i = 0; i < numberOfCompetitors; i++) {
        for (int j = 0; j < numberOfColumns; j++) {
            if (SHEET_TYPE_AVERAGE5S.equals(template.getSheetName())) {
                String range = "E" + (i + 5) + ":" + "I" + (i + 5);
                switch (j) {
                // rank
                case 0:
                    Cell rank = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    rank.setCellFormula("IF(COUNTBLANK(B" + (i + 5) + ")>0,\"\",IF(AND(M" + (i + 4) + "=M"
                            + (i + 5) + ",J" + (i + 4) + "=J" + (i + 5) + "),A" + (i + 4) + ",ROW()-4))");
                    break;
                // best
                case 9:
                    Cell best = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    best.setCellFormula("IF(MIN(" + range + ")>0,MIN(" + range + "),IF(COUNTBLANK(" + range
                            + ")=5,\"\",\"DNF\"))");
                    break;
                // worst
                case 11:
                    Cell worst = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    worst.setCellFormula("IF(COUNTBLANK(" + range + ")>0,\"\",IF(COUNTIF(" + range
                            + ",\"DNF\")+COUNTIF(" + range + ",\"DNS\")>0,\"DNF\",MAX(" + range + ")))");
                    break;
                // average
                case 12:
                    Cell average = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    average.setCellFormula("IF(COUNTBLANK(" + range + ")>0,\"\",IF(COUNTIF(" + range
                            + ",\"DNF\")+COUNTIF(" + range + ",\"DNS\")>1,\"DNF\",ROUND(IF(COUNTIF(" + range
                            + ",\"DNF\")+COUNTIF(" + range + ",\"DNS\")>0,(SUM(" + range + ")-J" + (i + 5)
                            + ")/3,(SUM(" + range + ")-J" + (i + 5) + "-L" + (i + 5) + ")/3),2)))");
                    break;
                }
            } else if (SHEET_TYPE_AVERAGE5M.equals(template.getSheetName())) {
                String range = "E" + (i + 5) + ":" + "I" + (i + 5);
                switch (j) {
                // rank
                case 0:
                    Cell rank = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    rank.setCellFormula("IF(COUNTBLANK(B" + (i + 5) + ")>0,\"\",IF(AND(M" + (i + 4) + "=M"
                            + (i + 5) + ",J" + (i + 4) + "=J" + (i + 5) + "),A" + (i + 4) + ",ROW()-4))");
                    break;
                // best
                case 9:
                    Cell best = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    best.setCellFormula("IF(MIN(" + range + ")>0,MIN(" + range + "),IF(COUNTBLANK(" + range
                            + ")=5,\"\",\"DNF\"))");
                    break;
                // worst
                case 11:
                    Cell worst = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    worst.setCellFormula("IF(COUNTBLANK(" + range + ")>0,\"\",IF(COUNTIF(" + range
                            + ",\"DNF\")+COUNTIF(" + range + ",\"DNS\")>0,\"DNF\",MAX(" + range + ")))");
                    break;
                // average
                case 12:
                    Cell average = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    average.setCellFormula("IF(COUNTBLANK(" + range + ")>0,\"\",IF(COUNTIF(" + range
                            + ",\"DNF\")+COUNTIF(" + range + ",\"DNS\")>1,\"DNF\",IF(COUNTIF(" + range
                            + ",\"DNF\")+COUNTIF(" + range + ",\"DNS\")>0,(SUM(" + range + ")-J" + (i + 5)
                            + ")/3,(SUM(" + range + ")-J" + (i + 5) + "-L" + (i + 5) + ")/3)))");
                    break;
                }
            } else if (SHEET_TYPE_MEAN3S.equals(template.getSheetName())) {
                String range = "E" + (i + 5) + ":" + "G" + (i + 5);
                switch (j) {
                // rank
                case 0:
                    Cell rank = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    rank.setCellFormula("IF(COUNTBLANK(B" + (i + 5) + ")>0,\"\",IF(AND(H" + (i + 4) + "=H"
                            + (i + 5) + ",J" + (i + 4) + "=J" + (i + 5) + "),A" + (i + 4) + ",ROW()-4))");
                    break;
                // best
                case 7:
                    Cell best = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    best.setCellFormula("IF(MIN(" + range + ")>0,MIN(" + range + "),IF(COUNTBLANK(" + range
                            + ")=3,\"\",\"DNF\"))");
                    break;
                // mean
                case 9:
                    Cell mean = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    mean.setCellFormula(
                            "IF(COUNTBLANK(" + range + ")>0,\"\",IF(COUNTIF(" + range + ",\"DNF\")+COUNTIF("
                                    + range + ",\"DNS\")>0,\"DNF\",ROUND(AVERAGE(" + range + "),2)))");
                    break;
                }
            } else if (SHEET_TYPE_MEAN3M.equals(template.getSheetName())) {
                String range = "E" + (i + 5) + ":" + "G" + (i + 5);
                switch (j) {
                // rank
                case 0:
                    Cell rank = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    rank.setCellFormula("IF(COUNTBLANK(B" + (i + 5) + ")>0,\"\",IF(AND(H" + (i + 4) + "=H"
                            + (i + 5) + ",J" + (i + 4) + "=J" + (i + 5) + "),A" + (i + 4) + ",ROW()-4))");
                    break;
                // best
                case 7:
                    Cell best = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    best.setCellFormula("IF(MIN(" + range + ")>0,MIN(" + range + "),IF(COUNTBLANK(" + range
                            + ")=3,\"\",\"DNF\"))");
                    break;
                // mean
                case 9:
                    Cell mean = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    mean.setCellFormula("IF(COUNTBLANK(" + range + ")>0,\"\",IF(COUNTIF(" + range
                            + ",\"DNF\")+COUNTIF(" + range + ",\"DNS\")>0,\"DNF\",AVERAGE(" + range + ")))");
                    break;
                }
            } else if (SHEET_TYPE_BEST1S.equals(template.getSheetName())
                    || SHEET_TYPE_BEST1M.equals(template.getSheetName())
                    || SHEET_TYPE_BEST1N.equals(template.getSheetName())) {
                switch (j) {
                // rank
                case 0:
                    Cell rank = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    rank.setCellFormula("IF(COUNTBLANK(B" + (i + 5) + ")>0,\"\",IF(E" + (i + 4) + "=E" + (i + 5)
                            + ",A" + (i + 4) + ",ROW()-4))");
                    break;
                }
            } else if (SHEET_TYPE_TEAMBEST1M.equals(template.getSheetName())) {
                switch (j) {
                // rank
                case 0:
                    Cell rank = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    rank.setCellFormula("IF(COUNTBLANK(B" + (i + 5) + ")>0,\"\",IF(H" + (i + 4) + "=H" + (i + 5)
                            + ",A" + (i + 4) + ",ROW()-4))");
                    break;
                }
            } else if (SHEET_TYPE_BEST2S.equals(template.getSheetName())
                    || SHEET_TYPE_BEST2M.equals(template.getSheetName())
                    || SHEET_TYPE_BEST2N.equals(template.getSheetName())) {
                String range = "E" + (i + 5) + ":" + "F" + (i + 5);
                switch (j) {
                // rank
                case 0:
                    Cell rank = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    rank.setCellFormula("IF(COUNTBLANK(B" + (i + 5) + ")>0,\"\",IF(G" + (i + 4) + "=G" + (i + 5)
                            + ",A" + (i + 4) + ",ROW()-4))");
                    break;
                // best
                case 6:
                    Cell best = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    best.setCellFormula("IF(MIN(" + range + ")>0,MIN(" + range + "),IF(COUNTBLANK(" + range
                            + ")=2,\"\",\"DNF\"))");
                    break;
                }
            } else if (SHEET_TYPE_TEAMBEST2M.equals(template.getSheetName())) {
                String range = "H" + (i + 5) + ":" + "I" + (i + 5);
                switch (j) {
                // rank
                case 0:
                    Cell rank = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    rank.setCellFormula("IF(COUNTBLANK(B" + (i + 5) + ")>0,\"\",IF(J" + (i + 4) + "=J" + (i + 5)
                            + ",A" + (i + 4) + ",ROW()-4))");
                    break;
                // best
                case 9:
                    Cell best = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    best.setCellFormula("IF(MIN(" + range + ")>0,MIN(" + range + "),IF(COUNTBLANK(" + range
                            + ")=2,\"\",\"DNF\"))");
                    break;
                }
            } else if (SHEET_TYPE_BEST3S.equals(template.getSheetName())
                    || SHEET_TYPE_BEST3M.equals(template.getSheetName())
                    || SHEET_TYPE_BEST3N.equals(template.getSheetName())) {
                String range = "E" + (i + 5) + ":" + "G" + (i + 5);
                switch (j) {
                // rank
                case 0:
                    Cell rank = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    rank.setCellFormula("IF(COUNTBLANK(B" + (i + 5) + ")>0,\"\",IF(H" + (i + 4) + "=H" + (i + 5)
                            + ",A" + (i + 4) + ",ROW()-4))");
                    break;
                // best
                case 7:
                    Cell best = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    best.setCellFormula("IF(MIN(" + range + ")>0,MIN(" + range + "),IF(COUNTBLANK(" + range
                            + ")=3,\"\",\"DNF\"))");
                    break;
                }
            } else if (SHEET_TYPE_TEAMBEST3M.equals(template.getSheetName())) {
                String range = "H" + (i + 5) + ":" + "J" + (i + 5);
                switch (j) {
                // rank
                case 0:
                    Cell rank = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    rank.setCellFormula("IF(COUNTBLANK(B" + (i + 5) + ")>0,\"\",IF(K" + (i + 4) + "=K" + (i + 5)
                            + ",A" + (i + 4) + ",ROW()-4))");
                    break;
                // best
                case 10:
                    Cell best = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    best.setCellFormula("IF(MIN(" + range + ")>0,MIN(" + range + "),IF(COUNTBLANK(" + range
                            + ")=2,\"\",\"DNF\"))");
                    break;
                }
            } else if (SHEET_TYPE_MULTIBF1.equals(template.getSheetName())) {
                switch (j) {
                // rank
                case 0:
                    Cell rank = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    rank.setCellFormula("IF(COUNTBLANK(B" + (i + 5) + ")>0,\"\",IF(I" + (i + 4) + "=I" + (i + 5)
                            + ",A" + (i + 4) + ",ROW()-4))");
                    break;
                // result
                case 8:
                    Cell result = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    result.setCellFormula("IF(E" + (i + 5) + "-F" + (i + 5) + ">F" + (i + 5) + ",-1,(99-F"
                            + (i + 5) + "+E" + (i + 5) + "-F" + (i + 5) + ")*10000000+G" + (i + 5) + "*100+E"
                            + (i + 5) + "-F" + (i + 5) + ")");
                    break;
                }
            } else if (SHEET_TYPE_MULTIBF2.equals(template.getSheetName())) {
                switch (j) {
                // rank
                case 0:
                    Cell rank = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    rank.setCellFormula("IF(COUNTBLANK(B" + (i + 5) + ")>0,\"\",IF(I" + (i + 4) + "=I" + (i + 5)
                            + ",A" + (i + 4) + ",ROW()-4))");
                    break;
                // result1
                case 7:
                    Cell result1 = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    result1.setCellFormula("IF(E" + (i + 5) + "=\"DNS\",-2,IF(E" + (i + 5) + "-F" + (i + 5)
                            + ">F" + (i + 5) + ",-1,(99-F" + (i + 5) + "+E" + (i + 5) + "-F" + (i + 5)
                            + ")*10000000+G" + (i + 5) + "*100+E" + (i + 5) + "-F" + (i + 5) + "))");
                    break;
                // result2
                case 11:
                    Cell result2 = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    result2.setCellFormula("IF(I" + (i + 5) + "=\"DNS\",-2,IF(I" + (i + 5) + "-J" + (i + 5)
                            + ">J" + (i + 5) + ",-1,(99-J" + (i + 5) + "+I" + (i + 5) + "-J" + (i + 5)
                            + ")*10000000+K" + (i + 5) + "*100+I" + (i + 5) + "-J" + (i + 5) + "))");
                    break;
                // best
                case 12:
                    Cell best = getCell(resultSheet, i + 4, j, Cell.CELL_TYPE_FORMULA);
                    best.setCellFormula("IF(AND(H" + (i + 5) + "<0,L" + (i + 5) + "<0),-1,IF(" + (i + 5)
                            + "<0,L" + (i + 5) + ",IF(L" + (i + 5) + "<0,H" + (i + 5) + ",MIN(H" + (i + 5)
                            + ",L" + (i + 5) + "))))");
                    break;
                }
            } else {
                log.error("Unsupported sheet type: {}", template.getSheetName());
            }

            // set cell style
            Row row = resultSheet.getRow(i + 4);
            if (row != null) {
                Cell cell = row.getCell(j);
                if (cell != null) {
                    cell.setCellStyle(cellStyles.get(j));
                }
            }
        }
    }

    // fill sheet with competitors for this event
    if (includeCompetitors) {
        if (round == null) {
            try {
                generateCompetitorResultsRows(workBook, resultSheet, event);
            } catch (Exception e) {
                log.error("[{}] " + e.getLocalizedMessage(), e);
                throw new RuntimeException("Could not include competitors and results in this sheet.", e);
            }
        } else {
            try {
                generateCompetitorRows(workBook, resultSheet, competition.getCompetitorsByEvent(event), 4);
            } catch (Exception e) {
                log.error("[{}] " + e.getLocalizedMessage(), e);
                throw new RuntimeException("Could not include competitors in this sheet.", e);
            }
        }
    }
}