Example usage for org.apache.poi.ss.usermodel Name setRefersToFormula

List of usage examples for org.apache.poi.ss.usermodel Name setRefersToFormula

Introduction

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

Prototype

void setRefersToFormula(String formulaText);

Source Link

Document

Sets the formula that the name is defined to refer to.

Usage

From source file:org.cgiar.ccafs.marlo.action.center.capdev.ParticipantsAction.java

License:Open Source License

public void createDataValidator(Workbook wb, Sheet sheet, String[] data, String dataValidationName) {
    String reference = null;//  ww w. ja  va  2  s.co m

    /*
     * se escriben las listas con los datos en cada sheet deseada
     */
    for (int i = 0; i < data.length; i++) {
        final Row fila = sheet.createRow(i);
        final Cell celda = fila.createCell(0);
        celda.setCellValue(data[i]);
    }

    // se protege el sheet para evitar que el usuario lo modifique
    sheet.protectSheet("marlo-ciat");

    /*
     * se crea referencia la lista de datos con el que se creara el data validator
     */
    final Name namedCountry = wb.createName();
    namedCountry.setNameName(dataValidationName);
    reference = sheet.getSheetName() + "!$A$1:$A$" + data.length; // area de referencia
    namedCountry.setRefersToFormula(reference);

}

From source file:org.formulacompiler.spreadsheet.internal.excel.xls.saver.ExcelXLSSaver.java

License:Open Source License

private void saveNames(BaseSpreadsheet _wb, Workbook _xwb) {
    for (final Entry<String, CellRange> nd : _wb.getModelRangeNames().entrySet()) {
        final String name = nd.getKey();
        final CellRange ref = nd.getValue();
        final CellIndex from = ref.getFrom();
        final CellIndex to = ref.getTo();
        if (from.getSheetIndex() == to.getSheetIndex()) {
            final Name namedCel = _xwb.createName();
            namedCel.setNameName(name);// w  w  w .ja  v a 2  s .co  m
            namedCel.setRefersToFormula(ref.toString());
        }
    }
}

From source file:org.isatools.isacreatorconfigurator.configui.io.Utils.java

License:Open Source License

public static String createTableConfigurationEXL(String outputDir,
        Map<MappingObject, List<Display>> tableFields)
        throws DataNotCompleteException, InvalidFieldOrderException, IOException {

    String excelFileName = "ISA-config-template.xlsx";
    FileOutputStream fos = new FileOutputStream(outputDir + File.separator + excelFileName);

    String tableName = "";

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet hiddenSheet = workbook.createSheet("hiddenCV");

    Map<String, List<String>> nodups = new HashMap<String, List<String>>();
    XSSFSheet ontologyRestriction = workbook.createSheet("Restrictions");
    XSSFRow ontorow0 = ontologyRestriction.createRow((short) 0);

    ontorow0.createCell(0).setCellValue("Column Name");
    ontorow0.createCell(1).setCellValue("Ontology");
    ontorow0.createCell(2).setCellValue("Branch");
    ontorow0.createCell(3).setCellValue("Version");

    CreationHelper factory = workbook.getCreationHelper();

    //  int counting=0;
    //  int ontocounter=0;
    int lastposition = 0;

    for (MappingObject mo : tableFields.keySet()) {

        tableName = mo.getAssayName().replace("\\s", "");

        List<Display> elements = tableFields.get(mo);

        System.out.println("creating worksheet: " + tableName);

        //we create a table with 50 records by default for anything that is not an investigation file
        if (!tableName.contains("investigation")) {

            XSSFSheet tableSheet = workbook.createSheet(tableName);
            Drawing drawing = tableSheet.createDrawingPatriarch();
            CellStyle style = workbook.createCellStyle();
            XSSFRow rowAtIndex;//from   ww w.j a v  a2  s.  c o  m

            //we create 51 rows by default for each table
            for (int index = 0; index <= 50; index++) {
                rowAtIndex = tableSheet.createRow((short) index);
            }

            //the first row is the header we need to build from the configuration declaration
            XSSFRow header = tableSheet.getRow(0);

            //we now iterated through the element found in the xml table configuration
            for (int fieldIndex = 0; fieldIndex < elements.size(); fieldIndex++) {

                if (elements.get(fieldIndex).getFieldDetails() != null) {

                    if (elements.get(fieldIndex).getFieldDetails().isRequired() == true) {

                        XSSFCell cell = header.createCell(fieldIndex);
                        Font font = workbook.createFont();
                        font.setBoldweight(Font.BOLDWEIGHT_BOLD);

                        style.setFont(font);
                        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
                        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
                        font.setColor(IndexedColors.RED.index);
                        cell.setCellStyle(style);
                        //create the header field by setting to FieldName as Cell name
                        cell.setCellValue(elements.get(fieldIndex).getFieldDetails().getFieldName());
                        System.out.println("REQUIRED field number " + fieldIndex + " is: "
                                + elements.get(fieldIndex).getFieldDetails().getFieldName());

                        //using the ISA field description to create a Comment attached to the set
                        ClientAnchor anchor = factory.createClientAnchor();
                        Comment comment = drawing.createCellComment(anchor);
                        RichTextString rts = factory.createRichTextString(
                                elements.get(fieldIndex).getFieldDetails().getDescription());
                        comment.setString(rts);
                        cell.setCellComment(comment);
                        tableSheet.autoSizeColumn(fieldIndex);

                    } else {
                        XSSFCell cell = header.createCell(fieldIndex);
                        Font font = workbook.createFont();
                        font.setBoldweight(Font.BOLDWEIGHT_BOLD);

                        style.setFont(font);
                        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
                        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
                        font.setColor(IndexedColors.BLACK.index);
                        cell.setCellStyle(style);
                        //create the header field by setting to FieldName as Cell name
                        cell.setCellValue(elements.get(fieldIndex).getFieldDetails().getFieldName());
                        //using the ISA field description to create a Comment attached to the set
                        ClientAnchor anchor = factory.createClientAnchor();
                        Comment comment = drawing.createCellComment(anchor);
                        RichTextString rts = factory.createRichTextString(
                                elements.get(fieldIndex).getFieldDetails().getDescription());
                        comment.setString(rts);
                        cell.setCellComment(comment);
                        tableSheet.autoSizeColumn(fieldIndex);
                    }

                    //checking if the field requires controled values, i.e ISA datatype is List

                    if (elements.get(fieldIndex).getFieldDetails().getDatatype() == DataTypes.LIST) {

                        //create a hidden spreadsheet and named range with the list of val
                        //counting++; //incrementing the counter defining the position where to start the new namedrange in the hidden spreadsheet

                        //obtain the name of the ISA fields and extracting key information needed to create a unique name for the Named Range to be
                        String rangeName = elements.get(fieldIndex).getFieldDetails().getFieldName()
                                .replace("'", "").replace(" ", "").replace("Comment[", "")
                                .replace("ParameterValue[", "").replace("Characteristics[", "").replace("]", "")
                                .replace("(", "").replace(")", "");

                        //getting all the values allowed by the List Field
                        String[] fieldValues = elements.get(fieldIndex).getFieldDetails().getFieldList();

                        //System.out.println("CV : "+elements.get(fieldIndex).getFieldDetails().getFieldName()+ " values: "  + Arrays.asList(fieldValues).toString()+ "size :" +fieldValues.length);

                        //iterating through the values and creating a cell for each
                        for (int j = 0; j < fieldValues.length; j++) {
                            hiddenSheet.createRow(lastposition + j).createCell(0).setCellValue(fieldValues[j]);
                        }

                        Name namedCell = workbook.createName();

                        workbook.getNumberOfNames();

                        int k = 0;
                        int position = 0;

                        //this is to handle ISA Fields sharing the same name (in different assays)
                        //namedRanges in Excel must be unique

                        while (k < workbook.getNumberOfNames()) { //we can the total number of field to type list we have found so far.

                            //something already exists...
                            if (workbook.getNameAt(k).equals(rangeName)) {
                                // namedCell.setNameName(workbook.getNameAt(k).toString());
                                //no need to go further, we exit here and set the parameter position to use the value
                                position = k;
                                k = -1;
                            } else {
                                k++;
                            }
                        }

                        if (k > 0) { //this means this field already existed list of that type
                            //we name the new cell after it
                            namedCell.setNameName(rangeName + k);
                            System.out.println("Name Name: " + namedCell.getNameName());
                        } else { //there is already one, so we just point back to it using the position parameter
                            namedCell.setNameName(workbook.getNameAt(k).toString()); //workbook.getNameAt(position).toString()
                            System.out.println("Name Name: " + namedCell.getNameName());
                        }

                        int start = 0;
                        int end = 0;
                        start = lastposition + 1;
                        System.out.println("start: + " + start);
                        end = lastposition + fieldValues.length;
                        System.out.println("end: + " + end);

                        //                                    String reference ="hiddenCV"+"!"+convertNumToColString(0)+start+":"+ convertNumToColString(0)+end;
                        String reference = "hiddenCV" + "!$" + convertNumToColString(0) + "$" + start + ":$"
                                + convertNumToColString(0) + "$" + end;
                        namedCell.setRefersToFormula(reference);

                        start = 0;
                        end = 0;
                        DataValidationHelper validationHelper = new XSSFDataValidationHelper(tableSheet);
                        DataValidationConstraint constraint = validationHelper
                                .createFormulaListConstraint(reference);
                        CellRangeAddressList addressList = new CellRangeAddressList(1, 50, fieldIndex,
                                fieldIndex);

                        System.out.println("field index: " + fieldIndex);
                        DataValidation dataValidation = validationHelper.createValidation(constraint,
                                addressList);

                        tableSheet.addValidationData(dataValidation);

                        lastposition = lastposition + fieldValues.length;
                        System.out.println("lastposition: + " + lastposition);
                        System.out.println("reference: " + reference);
                    }

                    //                                //TODO: reformat date but this is pain in Excel
                    //                                if (elements.get(fieldIndex).getFieldDetails().getDatatype()== DataTypes.DATE) {
                    //                                    //do something
                    //                                }

                    //  If a default value has been specified in the ISAconfiguration, we set it in the Excel spreadsheet
                    if (elements.get(fieldIndex).getFieldDetails().getDefaultVal() != null) {
                        for (int i = 1; i < 51; i++) {
                            rowAtIndex = tableSheet.getRow(i);
                            XSSFCell cellThere = rowAtIndex.createCell(fieldIndex);
                            cellThere.setCellValue(elements.get(fieldIndex).getFieldDetails().getDefaultVal());
                        }
                    }

                    if (elements.get(fieldIndex).getFieldDetails().getDatatype() == DataTypes.ONTOLOGY_TERM) {
                        int count = elements.get(fieldIndex).getFieldDetails().getRecommmendedOntologySource()
                                .values().size();
                        Collection<RecommendedOntology> myList = elements.get(fieldIndex).getFieldDetails()
                                .getRecommmendedOntologySource().values();
                        for (RecommendedOntology recommendedOntology : myList) {
                            System.out.println("ONTOLOGY :" + recommendedOntology.getOntology());
                            try {
                                if (recommendedOntology.getOntology() != null) {
                                    ArrayList<String> ontoAttributes = new ArrayList<String>();
                                    ontoAttributes.add(recommendedOntology.getOntology().getOntologyID());
                                    ontoAttributes.add(recommendedOntology.getOntology().getOntologyVersion());
                                    //  ontocounter++;
                                    //                                              XSSFRow ontoRowj = ontologyRestriction.createRow(ontocounter);
                                    //                                              ontoRowj.createCell(0).setCellValue(elements.get(fieldIndex).getFieldDetails().getFieldName());
                                    //                                              ontoRowj.createCell(1).setCellValue(recommendedOntology.getOntology().getOntologyID());
                                    //                                              ontoRowj.createCell(3).setCellValue(recommendedOntology.getOntology().getOntologyVersion());

                                    if (recommendedOntology.getBranchToSearchUnder() != null) {
                                        System.out.println("ONTOLOGY BRANCH :"
                                                + recommendedOntology.getBranchToSearchUnder());
                                        //                                                  ontoRowj.createCell(2).setCellValue(recommendedOntology.getBranchToSearchUnder().toString());
                                        ontoAttributes
                                                .add(recommendedOntology.getBranchToSearchUnder().toString());
                                    } else {
                                        ontoAttributes.add("");
                                    }

                                    nodups.put(elements.get(fieldIndex).getFieldDetails().getFieldName(),
                                            ontoAttributes);
                                }
                            } catch (NullPointerException npe) {
                                System.out.println(npe);
                            }
                        }
                    }
                }
            }
        } else {

            //we now create with the Investigation Sheet
            XSSFSheet tableSheet = workbook.createSheet(tableName);

            Drawing drawing = tableSheet.createDrawingPatriarch();

            CellStyle style = workbook.createCellStyle();
            Font font = workbook.createFont();

            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            style.setFont(font);

            for (int fieldIndex = 0; fieldIndex < elements.size(); fieldIndex++) {
                XSSFRow row = tableSheet.createRow((short) fieldIndex);
                if (elements.get(fieldIndex).getFieldDetails() != null) {
                    XSSFCell cell = row.createCell(0);
                    //create the header field by setting to FieldName as Cell name
                    cell.setCellValue(elements.get(fieldIndex).getFieldDetails().getFieldName());

                    //using the ISA field description to create a Comment attached to the set
                    ClientAnchor anchor = factory.createClientAnchor();
                    Comment comment = drawing.createCellComment(anchor);
                    RichTextString rts = factory
                            .createRichTextString(elements.get(fieldIndex).getFieldDetails().getDescription());
                    comment.setString(rts);
                    cell.setCellComment(comment);
                    cell.setCellStyle(style);
                    tableSheet.autoSizeColumn(fieldIndex);

                    SheetConditionalFormatting sheetCF = tableSheet.getSheetConditionalFormatting();

                    //condition: if the output of the FIND function is equal to 1, then, set cell to a blue font
                    ConditionalFormattingRule rule = sheetCF
                            .createConditionalFormattingRule("FIND(Investigation,$A$1:$A$21)>1");
                    //ConditionalFormattingRule rule = sheetCF.createConditionalFormattingRule(ComparisonOperator.) ;
                    FontFormatting font1 = rule.createFontFormatting();
                    font1.setFontStyle(false, true);
                    font1.setFontColorIndex(IndexedColors.BLUE.index);

                    CellRangeAddress[] regions = { CellRangeAddress.valueOf("A1:A21") };

                    sheetCF.addConditionalFormatting(regions, rule);
                }
            }
            tableSheet.setSelected(true);
            workbook.setSheetOrder(tableName, 0);

        }
    }

    //writes the values of ontology resources used to restrict selection in ISA fields
    int compteur = 1;

    for (Map.Entry<String, List<String>> entry : nodups.entrySet()) {
        String key = entry.getKey();
        // Object value = entry.getValue();

        System.out.println("UNIQUE RESOURCE: " + key);
        XSSFRow ontoRowj = ontologyRestriction.createRow(compteur);
        ontoRowj.createCell(0).setCellValue(key);
        ontoRowj.createCell(1).setCellValue(entry.getValue().get(0));
        ontoRowj.createCell(2).setCellValue(entry.getValue().get(2));
        ontoRowj.createCell(3).setCellValue(entry.getValue().get(1));

        compteur++;

    }

    //moving support worksheet to be the rightmost sheets in the workbook.
    //if the table corresponds to the study sample table, we move it to first position
    if (tableName.toLowerCase().contains("studysample")) {
        workbook.setSheetOrder(tableName, 1);
    }
    workbook.setSheetOrder("hiddenCV", tableFields.keySet().size() + 1);
    workbook.setSheetOrder("Restrictions", tableFields.keySet().size() + 1);
    workbook.write(fos);
    fos.close();

    String message = "Files have been saved in ";

    if (outputDir.equals("")) {
        message += "this programs directory";
    } else {
        message += outputDir;
    }

    return message;
}

From source file:org.openelis.bean.QcChartReport1Bean.java

License:Open Source License

private void finishSheet(HSSFSheet sheet, HSSFWorkbook wb, String qcName, String qcType, String sheetName) {
    int i, columnIndex;
    ArrayList<DictionaryDO> tempQcColumns;
    DictionaryDO dict;/*from  www .  jav  a2 s . c o m*/
    HashSet<Integer> emptyColumns;
    Name rangeName;
    Row row;
    String rangeFormula;

    if (qcColumns != null && !qcColumns.isEmpty())
        row = sheet.getRow(32);
    else
        row = sheet.getRow(3);
    emptyColumns = new HashSet<Integer>();
    for (i = 0; i < row.getLastCellNum(); i++) {
        if (i >= maxChars.size() || maxChars.get(i) == 0)
            emptyColumns.add(i);
    }

    setHeaderCells(sheet, qcName, qcType, sheetName);

    if (qcColumns != null && !qcColumns.isEmpty()) {
        tempQcColumns = new ArrayList<DictionaryDO>();
        tempQcColumns.addAll(qcColumns);
        for (i = tempQcColumns.size() - 1; i > -1; i--) {
            if (emptyColumns.contains(i + 5)) {
                tempQcColumns.remove(i);
                removeColumn(sheet, i + 5);
                maxChars.remove(i + 5);
            }
        }

        rangeName = getName(wb, sheet, "RowNumber");
        if (rangeName == null) {
            rangeName = wb.createName();
            rangeName.setSheetIndex(wb.getSheetIndex(sheet));
            rangeName.setNameName("RowNumber");
        }
        rangeFormula = sheet.getSheetName() + "!$" + CellReference.convertNumToColString(0) + "$33:" + "$"
                + CellReference.convertNumToColString(0) + "$" + (sheet.getLastRowNum() + 1);
        rangeName.setRefersToFormula(rangeFormula);

        /*
         * Create named ranges for the graph to be able to locate the appropriate
         * data
         */
        columnIndex = 5;
        for (i = 0; i < tempQcColumns.size(); i++) {
            dict = tempQcColumns.get(i);
            if (!DataBaseUtil.isEmpty(dict.getCode())) {
                rangeName = getName(wb, sheet, dict.getCode());
                if (rangeName == null) {
                    rangeName = wb.createName();
                    rangeName.setSheetIndex(wb.getSheetIndex(sheet));
                    rangeName.setNameName(dict.getCode());
                }
                rangeFormula = rangeName.getRefersToFormula();
                if (rangeFormula != null && rangeFormula.length() > 0
                        && !"$A$2".equals(rangeFormula.substring(rangeFormula.indexOf("!") + 1)))
                    rangeFormula += ",";
                else
                    rangeFormula = "";
                rangeFormula += sheet.getSheetName() + "!$" + CellReference.convertNumToColString(columnIndex)
                        + "$33:" + "$" + CellReference.convertNumToColString(columnIndex) + "$"
                        + (sheet.getLastRowNum() + 1);
                rangeName.setRefersToFormula(rangeFormula);
            }
            columnIndex++;
        }
        /*
         * make each column wide enough to show the longest string in it; the
         * width for each column is set as the maximum number of characters in
         * that column multiplied by 256; this is because the default width of
         * one character is 1/256 units in Excel
         */
        for (i = 5; i < maxChars.size(); i++)
            sheet.setColumnWidth(i, maxChars.get(i) * 256);
    } else if (worksheetHeaders != null && worksheetHeaders.size() > 0) {
        /*
         * make each column wide enough to show the longest string in it; the
         * width for each column is set as the maximum number of characters in
         * that column multiplied by 256; this is because the default width of
         * one character is 1/256 units in Excel
         */
        for (i = 0; i < maxChars.size(); i++)
            sheet.setColumnWidth(i, maxChars.get(i) * 256);
    }

    wb.setSheetName(wb.getSheetIndex(sheet), sheetName);
    sheet.setForceFormulaRecalculation(true);
    maxChars.clear();
}

From source file:org.openelis.bean.WorksheetExcelHelperBean.java

License:Open Source License

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public WorksheetManager1 exportToExcel(WorksheetManager1 manager) throws Exception {
    boolean isEditable;
    int r, i, a, o, aCount, aTotal;
    ArrayList<WorksheetAnalysisViewDO> waList;
    ArrayList<WorksheetResultViewDO> wrList;
    ArrayList<WorksheetQcResultViewDO> wqrList;
    String cellNameIndex, posNum, outFileName;
    File outFile;/*from  w w  w  . jav a  2s  . co  m*/
    FileInputStream in;
    FileOutputStream out;
    HashMap<Integer, ArrayList<WorksheetAnalysisViewDO>> waMap;
    HashMap<Integer, ArrayList<WorksheetResultViewDO>> wrMap;
    HashMap<Integer, ArrayList<WorksheetQcResultViewDO>> wqrMap;
    HashMap<Integer, WorksheetAnalysisViewDO> waLinkMap;
    HashMap<String, HashMap<Integer, ArrayList<AnalyteParameterViewDO>>> apMap;
    HashMap<String, String> tCellNames;
    Cell cell;
    CellRangeAddressList /*statusCells, */ reportableColumn;
    DVConstraint /*statusConstraint, */ reportableConstraint;
    HSSFDataValidation /*statusValidation, */ reportableValidation;
    HSSFSheet resultSheet, overrideSheet;
    HSSFWorkbook wb;
    Name cellName;
    Row row, oRow, tRow;
    DictionaryDO formatDO;
    ReportStatus status;
    SimpleDateFormat dateTimeFormat;
    WorksheetAnalysisDO waLinkDO;

    status = new ReportStatus();
    status.setMessage("Exporting to Excel: Initializing");
    status.setPercentComplete(0);
    session.setAttribute("ExportToExcelStatus", status);

    dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    outFileName = getWorksheetOutputFileName(manager.getWorksheet().getId(),
            manager.getWorksheet().getSystemUserId());
    outFile = new File(outFileName);
    if (outFile.exists())
        throw new Exception(
                "An Excel file for this worksheet already exists, please delete it before trying to export");

    try {
        formatDO = dictionaryCache.getById(manager.getWorksheet().getFormatId());
    } catch (NotFoundException nfE) {
        formatDO = new DictionaryDO();
        formatDO.setEntry("DefaultTotal");
        formatDO.setSystemName("wf_total");
    } catch (Exception anyE) {
        throw new Exception("Error retrieving worksheet format: " + anyE.getMessage());
    }

    try {
        in = new FileInputStream(getWorksheetTemplateFileName(formatDO));
        wb = new HSSFWorkbook(in, true);
        createStyles(wb);
    } catch (FileNotFoundException fnfE) {
        try {
            wb = buildTemplate(formatDO);
            createStyles(wb);
        } catch (FileNotFoundException fnfE2) {
            throw new Exception("Error loading template file: " + fnfE2.getMessage());
        } catch (IOException ioE) {
            throw new Exception("Error loading workbook from template file: " + ioE.getMessage());
        }
    }

    loadStatuses();
    //        statusCells = new CellRangeAddressList();

    tCellNames = loadNamesByCellReference(wb);

    resultSheet = wb.getSheet("Worksheet");

    tRow = resultSheet.getRow(1);
    resultSheet.removeRow(tRow);

    overrideSheet = wb.getSheet("Overrides");

    status.setPercentComplete(5);
    session.setAttribute("ExportToExcelStatus", status);

    r = 1;
    o = 1;
    i = 0;
    aCount = 0;
    apMap = new HashMap<String, HashMap<Integer, ArrayList<AnalyteParameterViewDO>>>();
    waMap = new HashMap<Integer, ArrayList<WorksheetAnalysisViewDO>>();
    waLinkMap = new HashMap<Integer, WorksheetAnalysisViewDO>();
    wrMap = new HashMap<Integer, ArrayList<WorksheetResultViewDO>>();
    wqrMap = new HashMap<Integer, ArrayList<WorksheetQcResultViewDO>>();
    loadMaps(manager, waMap, waLinkMap, wrMap, wqrMap);
    aTotal = getAnalyses(manager).size();
    if (getItems(manager) != null) {
        for (WorksheetItemDO wiDO : getItems(manager)) {
            a = 0;
            waList = waMap.get(wiDO.getId());
            if (waList != null && waList.size() > 0) {
                for (WorksheetAnalysisViewDO waVDO : waList) {
                    aCount++;
                    status.setMessage("Exporting to Excel: Analysis " + aCount + " of " + aTotal);
                    status.setPercentComplete((int) (((double) (aCount - 1) / aTotal) * 90) + 5);
                    session.setAttribute("ExportToExcelStatus", status);

                    waLinkDO = waLinkMap.get(waVDO.getWorksheetAnalysisId());

                    row = resultSheet.createRow(r);

                    // position number
                    posNum = wiDO.getPosition().toString();
                    cell = row.createCell(0);
                    cell.setCellStyle(styles.get("row_no_edit"));
                    if (a == 0)
                        cell.setCellValue(posNum);

                    // accession number
                    cell = row.createCell(1);
                    cell.setCellStyle(styles.get("row_no_edit"));
                    cell.setCellValue(waVDO.getAccessionNumber());

                    cellNameIndex = i + "." + a;
                    if (waVDO.getAnalysisId() != null) {
                        isEditable = (waVDO.getFromOtherId() == null
                                && !Constants.dictionary().ANALYSIS_INPREP.equals(waVDO.getStatusId())
                                && !Constants.dictionary().ANALYSIS_RELEASED.equals(waVDO.getStatusId())
                                && !Constants.dictionary().ANALYSIS_CANCELLED.equals(waVDO.getStatusId()));

                        // description
                        cell = row.createCell(2);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue(waVDO.getDescription());

                        // qc link
                        cell = row.createCell(3);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        if (waLinkDO != null)
                            cell.setCellValue(waLinkDO.getAccessionNumber());
                        else
                            cell.setCellValue("");

                        // test name
                        cell = row.createCell(4);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue(waVDO.getTestName());

                        // method name
                        cell = row.createCell(5);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue(waVDO.getMethodName());

                        // analysis status
                        cell = row.createCell(6);
                        //                            if (isEditable)
                        //                                cell.setCellStyle(styles.get("row_edit"));
                        //                            else
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue(statusIdNameMap.get(waVDO.getStatusId()));
                        cellName = wb.createName();
                        cellName.setNameName("analysis_status." + i + "." + a);
                        cellName.setRefersToFormula("Worksheet!$" + CellReference.convertNumToColString(6) + "$"
                                + (row.getRowNum() + 1));
                        //                            statusCells.addCellRangeAddress(r, 6, r, 6);

                        wrList = wrMap.get(waVDO.getId());
                        if (wrList == null || wrList.size() == 0) {
                            // analyte
                            cell = row.createCell(7);
                            cell.setCellStyle(styles.get("row_no_edit"));
                            cell.setCellValue("NO ANALYTES DEFINED");

                            // reportable
                            cell = row.createCell(8);
                            cell.setCellStyle(styles.get("row_no_edit"));
                            cell.setCellValue("N");

                            createEmptyCellsForFormat(row, tRow);
                            r++;
                        } else {
                            r = createResultCellsForFormat(resultSheet, row, tRow, cellNameIndex, tCellNames,
                                    manager.getWorksheet(), waVDO, wrList, isEditable, apMap);
                        }

                        //
                        // Add override row to override sheet
                        //
                        oRow = overrideSheet.createRow(o);

                        // position number
                        cell = oRow.createCell(0);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        if (a == 0)
                            cell.setCellValue(posNum);

                        // accession number
                        cell = oRow.createCell(1);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue(waVDO.getAccessionNumber());

                        // description (override)
                        cell = oRow.createCell(2);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue(waVDO.getDescription());

                        // test name (overrride)
                        cell = oRow.createCell(3);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue(waVDO.getTestName());

                        // method name (override)
                        cell = oRow.createCell(4);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue(waVDO.getMethodName());

                        // users (override)
                        cell = oRow.createCell(5);
                        if (isEditable)
                            cell.setCellStyle(styles.get("row_edit"));
                        else
                            cell.setCellStyle(styles.get("row_no_edit"));
                        if (waVDO.getSystemUsers() != null)
                            cell.setCellValue(waVDO.getSystemUsers());
                        cellName = wb.createName();
                        cellName.setNameName("analysis_users." + cellNameIndex);
                        cellName.setRefersToFormula("Overrides!$" + CellReference.convertNumToColString(5) + "$"
                                + (oRow.getRowNum() + 1));

                        // started (override)
                        cell = oRow.createCell(6);
                        if (isEditable)
                            cell.setCellStyle(styles.get("datetime_edit"));
                        else
                            cell.setCellStyle(styles.get("datetime_no_edit"));
                        if (waVDO.getStartedDate() != null)
                            cell.setCellValue(dateTimeFormat.format(waVDO.getStartedDate().getDate()));
                        cellName = wb.createName();
                        cellName.setNameName("analysis_started." + cellNameIndex);
                        cellName.setRefersToFormula("Overrides!$" + CellReference.convertNumToColString(6) + "$"
                                + (oRow.getRowNum() + 1));

                        // completed (override)
                        cell = oRow.createCell(7);
                        if (isEditable)
                            cell.setCellStyle(styles.get("datetime_edit"));
                        else
                            cell.setCellStyle(styles.get("datetime_no_edit"));
                        if (waVDO.getCompletedDate() != null)
                            cell.setCellValue(dateTimeFormat.format(waVDO.getCompletedDate().getDate()));
                        cellName = wb.createName();
                        cellName.setNameName("analysis_completed." + cellNameIndex);
                        cellName.setRefersToFormula("Overrides!$" + CellReference.convertNumToColString(7) + "$"
                                + (oRow.getRowNum() + 1));
                        o++;
                    } else if (waVDO.getQcLotId() != null) {
                        // description
                        cell = row.createCell(2);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue(waVDO.getDescription());

                        // qc link
                        cell = row.createCell(3);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        if (waLinkDO != null)
                            cell.setCellValue(waLinkDO.getAccessionNumber());
                        else
                            cell.setCellValue("");

                        // test name
                        cell = row.createCell(4);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue("");

                        // method name
                        cell = row.createCell(5);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue("");

                        // analysis status
                        cell = row.createCell(6);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue("");

                        wqrList = wqrMap.get(waVDO.getId());
                        if (wqrList == null || wqrList.size() == 0) {
                            // analyte
                            cell = row.createCell(7);
                            cell.setCellStyle(styles.get("row_no_edit"));
                            cell.setCellValue("NO ANALYTES DEFINED");

                            // reportable
                            cell = row.createCell(8);
                            cell.setCellStyle(styles.get("row_no_edit"));
                            cell.setCellValue("N");

                            createEmptyCellsForFormat(row, tRow);

                            r++;
                        } else {
                            cellNameIndex = i + "." + a;
                            r = createQcResultCellsForFormat(resultSheet, row, tRow, cellNameIndex, tCellNames,
                                    manager.getWorksheet(), waVDO.getQcId(), wqrList, apMap);
                        }

                        //
                        // Add override row to override sheet
                        //
                        oRow = overrideSheet.createRow(o);

                        // position number
                        cell = oRow.createCell(0);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        if (a == 0)
                            cell.setCellValue(posNum);

                        // accession number
                        cell = oRow.createCell(1);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue(waVDO.getAccessionNumber());

                        // description (override)
                        cell = oRow.createCell(2);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue(waVDO.getDescription());

                        // test name (overrride)
                        cell = oRow.createCell(3);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue("");

                        // method name (override)
                        cell = oRow.createCell(4);
                        cell.setCellStyle(styles.get("row_no_edit"));
                        cell.setCellValue("");

                        // users (override)
                        cell = oRow.createCell(5);
                        cell.setCellStyle(styles.get("row_edit"));
                        if (waVDO.getSystemUsers() != null)
                            cell.setCellValue(waVDO.getSystemUsers());
                        cellName = wb.createName();
                        cellName.setNameName("analysis_users." + cellNameIndex);
                        cellName.setRefersToFormula("Overrides!$" + CellReference.convertNumToColString(5) + "$"
                                + (oRow.getRowNum() + 1));

                        // started (override)
                        cell = oRow.createCell(6);
                        cell.setCellStyle(styles.get("datetime_edit"));
                        if (waVDO.getStartedDate() != null)
                            cell.setCellValue(dateTimeFormat.format(waVDO.getStartedDate().getDate()));
                        cellName = wb.createName();
                        cellName.setNameName("analysis_started." + cellNameIndex);
                        cellName.setRefersToFormula("Overrides!$" + CellReference.convertNumToColString(6) + "$"
                                + (oRow.getRowNum() + 1));

                        // completed (override)
                        cell = oRow.createCell(7);
                        cell.setCellStyle(styles.get("datetime_no_edit"));
                        cellName = wb.createName();
                        cellName.setNameName("analysis_completed." + cellNameIndex);
                        cellName.setRefersToFormula("Overrides!$" + CellReference.convertNumToColString(7) + "$"
                                + (oRow.getRowNum() + 1));
                        o++;
                    }

                    a++;
                }
            }

            i++;
        }
    }

    status.setMessage("Exporting to Excel: Finalizing");
    status.setPercentComplete(95);
    session.setAttribute("ExportToExcelStatus", status);

    //
    // Create validators
    //
    //        statusConstraint = DVConstraint.createExplicitListConstraint(statuses);
    //        statusValidation = new HSSFDataValidation(statusCells, statusConstraint);
    //        statusValidation.setEmptyCellAllowed(true);
    //        statusValidation.setSuppressDropDownArrow(false);
    //        statusValidation.createPromptBox("Statuses", formatTooltip(statuses));
    //        statusValidation.setShowPromptBox(false);
    //        resultSheet.addValidationData(statusValidation);

    reportableColumn = new CellRangeAddressList(1, resultSheet.getPhysicalNumberOfRows() - 1, 8, 8);
    reportableConstraint = DVConstraint.createExplicitListConstraint(new String[] { "Y", "N" });
    reportableValidation = new HSSFDataValidation(reportableColumn, reportableConstraint);
    reportableValidation.setSuppressDropDownArrow(false);
    resultSheet.addValidationData(reportableValidation);

    //
    // Auto resize columns on result sheet and override sheet
    //
    resultSheet.autoSizeColumn(2, true); // Description
    resultSheet.autoSizeColumn(4, true); // Test
    resultSheet.autoSizeColumn(5, true); // Method
    resultSheet.autoSizeColumn(7, true); // Analyte

    overrideSheet.autoSizeColumn(2, true); // Description
    overrideSheet.autoSizeColumn(3, true); // Test
    overrideSheet.autoSizeColumn(4, true); // Method

    try {
        out = new FileOutputStream(outFileName);
        wb.write(out);
        out.close();
        Runtime.getRuntime().exec("chmod go+rw " + outFileName);
    } catch (Exception anyE) {
        throw new Exception("Error writing Excel file: " + anyE.getMessage());
    }

    status.setMessage("Exporting to Excel: Done");
    status.setPercentComplete(100);
    session.setAttribute("ExportToExcelStatus", status);

    return manager;
}

From source file:org.openelis.bean.WorksheetExcelHelperBean.java

License:Open Source License

private HSSFWorkbook buildTemplate(DictionaryDO formatDO) throws Exception {
    int c;//from   w ww .j  a v a  2  s .c  om
    ArrayList<DictionaryDO> formatColumns;
    Cell hCell, tCell;
    FileInputStream in;
    HSSFSheet resultSheet;
    HSSFWorkbook wb;
    Name cellName;
    Row hRow, tRow;

    in = new FileInputStream(getWorksheetTemplateFileName("Base"));
    wb = new HSSFWorkbook(in, true);
    createStyles(wb);

    try {
        formatColumns = categoryCache.getBySystemName(formatDO.getSystemName()).getDictionaryList();
    } catch (Exception anyE) {
        throw new Exception("Error retrieving worksheet format: " + anyE.getMessage());
    }

    c = 9;
    resultSheet = wb.getSheet("Worksheet");
    hRow = resultSheet.getRow(0);
    tRow = resultSheet.getRow(1);
    for (DictionaryDO columnDO : formatColumns) {
        hCell = hRow.createCell(c);
        hCell.setCellStyle(styles.get("header"));
        hCell.setCellValue(columnDO.getEntry());

        tCell = tRow.createCell(c);
        tCell.setCellStyle(styles.get("row_edit"));

        cellName = wb.createName();
        cellName.setNameName(columnDO.getSystemName().substring(formatDO.getSystemName().length()));
        cellName.setRefersToFormula(
                "Worksheet!$" + CellReference.convertNumToColString(c) + "$" + (tRow.getRowNum() + 1));

        resultSheet.autoSizeColumn(c, true);
        c++;
    }

    return wb;
}

From source file:org.openelis.bean.WorksheetExcelHelperBean.java

License:Open Source License

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
private int createResultCellsForFormat(HSSFSheet sheet, Row row, Row tRow, String nameIndexPrefix,
        HashMap<String, String> cellNames, WorksheetViewDO wVDO, WorksheetAnalysisViewDO waVDO,
        ArrayList<WorksheetResultViewDO> wrList, boolean isEditable,
        HashMap<String, HashMap<Integer, ArrayList<AnalyteParameterViewDO>>> apMap) {
    int c, i, r;/* w w  w . j a v  a  2 s  . c o m*/
    String cellNameIndex, name;
    ArrayList<AnalyteParameterViewDO> anaParams, apList;
    DecimalFormat df;
    HashMap<Integer, ArrayList<AnalyteParameterViewDO>> pMap;
    Cell cell, tCell;
    Name cellName;
    AnalyteParameterViewDO apVDO;

    df = new DecimalFormat();
    df.setGroupingUsed(false);
    df.setMaximumFractionDigits(10);

    i = 0;
    r = row.getRowNum();
    for (WorksheetResultViewDO wrVDO : wrList) {
        if (i != 0) {
            row = sheet.createRow(r);
            for (c = 0; c < 7; c++) {
                cell = row.createCell(c);
                cell.setCellStyle(styles.get("row_no_edit"));
            }
        }

        cellNameIndex = nameIndexPrefix + "." + i;

        // analyte
        cell = row.createCell(7);
        cell.setCellStyle(styles.get("row_no_edit"));
        cell.setCellValue(wrVDO.getAnalyteName());

        // reportable
        cell = row.createCell(8);
        cell.setCellStyle(styles.get("row_no_edit"));
        cell.setCellValue(wrVDO.getIsReportable());
        cellName = sheet.getWorkbook().createName();
        cellName.setNameName("analyte_reportable." + cellNameIndex);
        cellName.setRefersToFormula(
                "Worksheet!$" + CellReference.convertNumToColString(8) + "$" + (row.getRowNum() + 1));

        apVDO = null;
        for (c = 9; c < tRow.getLastCellNum() && c < 39; c++) {
            tCell = tRow.getCell(c);

            cell = row.createCell(c);
            if (isEditable)
                cell.setCellStyle(tCell.getCellStyle());
            else
                cell.setCellStyle(styles.get("row_no_edit"));
            name = cellNames.get(
                    sheet.getSheetName() + "!$" + CellReference.convertNumToColString(tCell.getColumnIndex())
                            + "$" + (tCell.getRowIndex() + 1));
            if (name != null) {
                cellName = row.getSheet().getWorkbook().createName();
                cellName.setNameName(name + "." + cellNameIndex);
                cellName.setRefersToFormula(
                        sheet.getSheetName() + "!$" + CellReference.convertNumToColString(cell.getColumnIndex())
                                + "$" + (row.getRowNum() + 1));
            }
            if (tCell.getCellType() == Cell.CELL_TYPE_FORMULA && tCell.getCellFormula() != null) {
                cell.setCellFormula(tCell.getCellFormula());
            } else {
                setCellValue(cell, wrVDO.getValueAt(c - 9));
            }
            if ("p1".equals(name) || "p2".equals(name) || "p3".equals(name) || "p_1".equals(name)
                    || "p_2".equals(name) || "p_3".equals(name)) {
                if (wrVDO.getValueAt(c - 9) == null) {
                    pMap = apMap.get("T" + waVDO.getTestId());
                    if (pMap == null) {
                        pMap = new HashMap<Integer, ArrayList<AnalyteParameterViewDO>>();
                        apMap.put("T" + waVDO.getTestId(), pMap);
                        try {
                            anaParams = analyteParameter.fetchByActiveDate(waVDO.getTestId(),
                                    Constants.table().TEST, wVDO.getCreatedDate().getDate());
                            for (AnalyteParameterViewDO anaParam : anaParams) {
                                apList = pMap.get(anaParam.getAnalyteId());
                                if (apList == null) {
                                    apList = new ArrayList<AnalyteParameterViewDO>();
                                    pMap.put(anaParam.getAnalyteId(), apList);
                                }
                                apList.add(anaParam);
                            }
                        } catch (NotFoundException nfE) {
                            continue;
                        } catch (Exception anyE) {
                            log.log(Level.SEVERE,
                                    "Error retrieving analyte parameters for an analysis on worksheet.", anyE);
                            continue;
                        }
                    }

                    apList = pMap.get(wrVDO.getAnalyteId());
                    apVDO = null;
                    if (apList != null && apList.size() > 0) {
                        for (AnalyteParameterViewDO ap : apList) {
                            if (ap.getUnitOfMeasureId() == null
                                    || ap.getUnitOfMeasureId().equals(waVDO.getUnitOfMeasureId())) {
                                if (ap.getUnitOfMeasureId() != null) {
                                    apVDO = ap;
                                    break;
                                } else if (apVDO == null) {
                                    apVDO = ap;
                                }
                            }
                        }
                    }
                    if (apVDO != null) {
                        if (("p1".equals(name) || "p_1".equals(name)) && apVDO.getP1() != null) {
                            setCellValue(cell, df.format(apVDO.getP1()));
                        } else if (("p2".equals(name) || "p_2".equals(name)) && apVDO.getP2() != null) {
                            setCellValue(cell, df.format(apVDO.getP2()));
                        } else if (("p3".equals(name) || "p_3".equals(name)) && apVDO.getP3() != null) {
                            setCellValue(cell, df.format(apVDO.getP3()));
                        }
                    }
                }
            }
        }

        i++;
        r++;
    }

    return r;
}

From source file:org.openelis.bean.WorksheetExcelHelperBean.java

License:Open Source License

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
private int createQcResultCellsForFormat(HSSFSheet sheet, Row row, Row tRow, String nameIndexPrefix,
        HashMap<String, String> cellNames, WorksheetViewDO wVDO, Integer qcId,
        ArrayList<WorksheetQcResultViewDO> wqrList,
        HashMap<String, HashMap<Integer, ArrayList<AnalyteParameterViewDO>>> apMap) {
    int c, i, r;//from ww w. j  ava  2 s . c  o  m
    String cellNameIndex, name;
    ArrayList<AnalyteParameterViewDO> anaParams, apList;
    DecimalFormat df;
    HashMap<Integer, ArrayList<AnalyteParameterViewDO>> pMap;
    Cell cell, tCell;
    Name cellName;
    AnalyteParameterViewDO apVDO;

    df = new DecimalFormat();
    df.setGroupingUsed(false);
    df.setMaximumFractionDigits(10);

    i = 0;
    r = row.getRowNum();
    for (WorksheetQcResultViewDO wqrVDO : wqrList) {
        if (i != 0) {
            row = sheet.createRow(r);
            for (c = 0; c < 7; c++) {
                cell = row.createCell(c);
                cell.setCellStyle(styles.get("row_no_edit"));
            }
        }

        cellNameIndex = nameIndexPrefix + "." + i;

        // analyte
        cell = row.createCell(7);
        cell.setCellStyle(styles.get("row_no_edit"));
        cell.setCellValue(wqrVDO.getAnalyteName());

        // reportable
        cell = row.createCell(8);
        cell.setCellStyle(styles.get("row_no_edit"));
        cell.setCellValue("N");

        apVDO = null;
        for (c = 9; c < tRow.getLastCellNum() && c < 39; c++) {
            tCell = tRow.getCell(c);

            cell = row.createCell(c);
            cell.setCellStyle(tCell.getCellStyle());
            name = cellNames.get(
                    sheet.getSheetName() + "!$" + CellReference.convertNumToColString(tCell.getColumnIndex())
                            + "$" + (tCell.getRowIndex() + 1));
            if (name != null) {
                cellName = row.getSheet().getWorkbook().createName();
                cellName.setNameName(name + "." + cellNameIndex);
                cellName.setRefersToFormula(
                        sheet.getSheetName() + "!$" + CellReference.convertNumToColString(cell.getColumnIndex())
                                + "$" + (row.getRowNum() + 1));
            }
            if (tCell.getCellType() == Cell.CELL_TYPE_FORMULA && tCell.getCellFormula() != null) {
                cell.setCellFormula(tCell.getCellFormula());
            } else {
                setCellValue(cell, wqrVDO.getValueAt(c - 9));
            }
            if ("p1".equals(name) || "p2".equals(name) || "p3".equals(name) || "p_1".equals(name)
                    || "p_2".equals(name) || "p_3".equals(name)) {
                if (wqrVDO.getValueAt(c - 9) == null) {
                    pMap = apMap.get("Q" + qcId);
                    if (pMap == null) {
                        pMap = new HashMap<Integer, ArrayList<AnalyteParameterViewDO>>();
                        apMap.put("Q" + qcId, pMap);
                        try {
                            anaParams = analyteParameter.fetchByActiveDate(qcId, Constants.table().QC,
                                    wVDO.getCreatedDate().getDate());
                            for (AnalyteParameterViewDO anaParam : anaParams) {
                                apList = pMap.get(anaParam.getAnalyteId());
                                if (apList == null) {
                                    apList = new ArrayList<AnalyteParameterViewDO>();
                                    pMap.put(anaParam.getAnalyteId(), apList);
                                }
                                apList.add(anaParam);
                            }
                        } catch (NotFoundException nfE) {
                            continue;
                        } catch (Exception anyE) {
                            log.log(Level.SEVERE, "Error retrieving analyte parameters for a qc on worksheet.",
                                    anyE);
                            continue;
                        }
                    }

                    apList = pMap.get(wqrVDO.getAnalyteId());
                    apVDO = null;
                    if (apList != null && apList.size() > 0)
                        apVDO = apList.get(0);
                    if (apVDO != null) {
                        if (("p1".equals(name) || "p_1".equals(name)) && apVDO.getP1() != null) {
                            setCellValue(cell, String.valueOf(apVDO.getP1()));
                        } else if (("p2".equals(name) || "p_2".equals(name)) && apVDO.getP2() != null) {
                            setCellValue(cell, String.valueOf(apVDO.getP2()));
                        } else if (("p3".equals(name) || "p_3".equals(name)) && apVDO.getP3() != null) {
                            setCellValue(cell, String.valueOf(apVDO.getP3()));
                        }
                    }
                }
            }
        }

        i++;
        r++;
    }

    return r;
}

From source file:uk.ac.manchester.cs.owl.semspreadsheets.model.xssf.impl.WorkbookXSSFImpl.java

License:Open Source License

public void addName(String name, Range rng) {
    if (workbook.getName(name) != null) {
        workbook.removeName(name);/* w w w.ja  v a2s.  com*/
    }
    Name xssfName = workbook.createName();
    xssfName.setNameName(name);
    xssfName.setRefersToFormula(rng.toFixedAddress());
}

From source file:uk.co.spudsoft.birt.emitters.excel.handlers.AbstractHandler.java

License:Open Source License

protected void createName(HandlerState state, String bookmark, int row1, int col1, int row2, int col2) {
    CellReference crFirst = new CellReference(state.currentSheet.getSheetName(), row1, col1, true, true);
    CellReference crLast = new CellReference(row2, col2, true, true);
    String formula = crFirst.formatAsString() + ":" + crLast.formatAsString();

    Name name = state.currentSheet.getWorkbook().getName(bookmark);
    if (name == null) {
        name = state.currentSheet.getWorkbook().createName();
        name.setNameName(bookmark);//from  w w  w.  ja v a 2 s . c  o m
        name.setRefersToFormula(formula);
    } else {
        String existingFormula = name.getRefersToFormula();
        try {
            name.setRefersToFormula(existingFormula + "," + formula);
        } catch (FormulaParseException ex) {
            log.warn(0, "Unable to add \"" + formula + "\" to name (\"" + bookmark
                    + "\") with existing formula: " + existingFormula, ex);
        }
    }
}