Example usage for org.apache.poi.ss.util CellRangeAddressList CellRangeAddressList

List of usage examples for org.apache.poi.ss.util CellRangeAddressList CellRangeAddressList

Introduction

In this page you can find the example usage for org.apache.poi.ss.util CellRangeAddressList CellRangeAddressList.

Prototype

public CellRangeAddressList(int firstRow, int lastRow, int firstCol, int lastCol) 

Source Link

Document

Convenience constructor for creating a CellRangeAddressList with a single CellRangeAddress.

Usage

From source file:de.bund.bfr.knime.openkrise.db.imports.custom.bfrnewformat.TraceGenerator.java

License:Open Source License

private void insertDecCondition(XSSFDataValidationHelper dvHelper, XSSFSheet sheetTracing, int row, int col) {
    XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper
            .createDecimalConstraint(OperatorType.GREATER_OR_EQUAL, "0", "");
    // dvConstraint = (XSSFDataValidationConstraint) dvHelper.createExplicitListConstraint(new String[]{"0000011", "0000021", "0000031"});
    CellRangeAddressList addressList = new CellRangeAddressList(row, row, col, col);
    XSSFDataValidation validation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint, addressList);
    validation.setShowErrorBox(true);/*from  w w w .  ja  v  a  2 s. com*/
    validation.setSuppressDropDownArrow(true);
    validation.setShowPromptBox(true);
    sheetTracing.addValidationData(validation);
}

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

License:Open Source License

/**
 * Adds dropdowns to cells in an enumeration value column. The number of formatted rows is defined by parameter {@code lastRow}.
 * /* w ww  . j  a v  a  2  s .  c  o  m*/
 * @param enumExpr
 *        The EnumerationPropertyExpression from which all enum literal are extracted for generating the dropdown.
 * @param sheetContext
 *        The Context for the relationship sheet that should be operated upon.
 * @param lastRow
 *        The number of the last row up to which rows are formatted with dropdowns
 */
private static void addDropdownToEnumeration(EnumerationPropertyExpression enumExpr, SheetContext sheetContext,
        int lastRow) {
    ColumnContext sheetColumn = sheetContext.getColumnByPersistentName(enumExpr.getPersistentName());
    List<String> values = getListOfLiterals(enumExpr);
    if (values.isEmpty() || StringUtils.join(values, ";").length() >= 255) {
        //do not add dropdown, since it would break export!
        return;
    }

    int columnIndex = sheetColumn.getColumnNumber();
    CellRangeAddressList addressList = new CellRangeAddressList(sheetContext.getFirstDataRowNumber(), lastRow,
            columnIndex, columnIndex);
    ExcelGeneratorUtils.createDropdownWithValues(sheetContext.getSheet(), addressList, values);
}

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

License:Open Source License

/**
 * Adds dropdowns to cells in a relationship column. The number of formatted rows is defined by parameter {@code dataSetSize}.
 * /*  w  w  w. j a  va 2s.co m*/
 * @param relationshipEndExpression
 *        The RelationshipEndExpression which determines the column that shall be formatted
 * @param sheetContext
 *        The Context for the relationship sheet that should be operated upon.
 * @param dataSetSize
 *        The number of rows to be formatted with dropdown
 */
public static void addDropdownsToRelationshipColumn(RelationshipEndExpression relationshipEndExpression,
        SheetContext sheetContext, int dataSetSize) {
    UniversalTypeExpression source = relationshipEndExpression.getType();
    String namesListFormula = ExcelGeneratorUtils.createNameForFormulaAllNames(source);
    ColumnContext column = sheetContext
            .getColumnByPersistentName(relationshipEndExpression.getPersistentName());
    int columnIndex = column.getColumnNumber();
    CellRangeAddressList addressList = new CellRangeAddressList(sheetContext.getFirstDataRowNumber(),
            sheetContext.calculateLastDataRow(dataSetSize), columnIndex, columnIndex);
    ExcelGeneratorUtils.createDropdown(sheetContext.getSheet(), addressList, namesListFormula);
}

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

License:Open Source License

/**
 * Adds dropdowns to cells in a parent relation column. The number of formatted rows is defined by parameter {@code dataSetSize}.
 * //from  ww  w .j  a v a2  s .  com
 * @param sheetContext
 *        The Context for the relationship sheet that should be operated upon.
 * @param dataSetSize
 *        The number of rows to be formatted with dropdown
 */
public static void addParentRelationDropDown(SheetContext sheetContext, int dataSetSize) {
    UniversalTypeExpression ute = (UniversalTypeExpression) sheetContext.getExpression();
    ColumnContext parentColumn = sheetContext.getColumnByPersistentName(SheetContext.PARENT_COLUMN);
    int parentCol = parentColumn.getColumnNumber();
    CellRangeAddressList addressList = new CellRangeAddressList(sheetContext.getFirstDataRowNumber(),
            sheetContext.calculateLastDataRow(dataSetSize), parentCol, parentCol);
    String namesListFormulaName = ExcelGeneratorUtils.createNameForFormulaAllNames(ute);
    ExcelGeneratorUtils.createDropdown(sheetContext.getSheet(), addressList, namesListFormulaName);
}

From source file:edu.casetools.rcase.extensions.excel.control.Exporter.java

License:Open Source License

/**
 * Creates the cell style.//from  www .  j a v a2 s . com
 *
 * @param sheet
 *            the sheet where to create the style.
 * @param rowNumber
 *            the row number where to create the style.
 * @param columnNumber
 *            the column number where to create the style.
 * @param cell
 *            the cell where to create the style.
 * @param cellTable
 *            the cell table where to create the style.
 * @return the column number
 */
protected int createCellStyle(Sheet sheet, int rowNumber, int columnNumber, Cell cell, TableCell cellTable) {
    int auxiliarColumnNumber = columnNumber;
    cell.setCellStyle(this.contentCellStyle);
    cell.setCellValue(cellTable.getValue());

    String[] possibleValues = cellTable.getPossibleValues();

    if (0 != possibleValues.length) {
        DataValidation validation;
        DataValidationConstraint constraint;
        CellRangeAddressList addressList = new CellRangeAddressList(rowNumber, rowNumber, auxiliarColumnNumber,
                auxiliarColumnNumber);
        if (this.version == SpreadsheetVersion.EXCEL2007) {
            validation = createExcel2007CellStyle(sheet, possibleValues, addressList);
        } else {
            constraint = DVConstraint.createExplicitListConstraint(possibleValues);
            validation = new HSSFDataValidation(addressList, constraint);
        }

        if (validation != null) {
            sheet.addValidationData(validation);
        }
    }
    auxiliarColumnNumber++;
    return auxiliarColumnNumber;
}

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

License:Open Source License

public String dowmloadTemplate() {
    try {//from  ww  w  . j  ava  2s  . co  m
        ClassLoader classLoader = this.getClass().getClassLoader();
        File file = new File(this.getClass().getResource("/template/participants-template.xlsm").getFile());

        String path = new File(".").getCanonicalPath();
        String real_path = path + "/src/main/resources/template/participants-template.xlsm";
        String path_ = config.getUploadsBaseFolder() + "/participants-template.xlsm";

        FileInputStream fileInput = new FileInputStream(path_);
        XSSFWorkbook wb = new XSSFWorkbook(fileInput);

        DataValidationConstraint constraintCountries = null;
        DataValidationConstraint constraintHighestDegree = null;
        DataValidationHelper validationHelper = null;

        Sheet sheet1 = wb.getSheetAt(0);
        XSSFSheet sheet2 = wb.getSheet("countries");

        String dataValidationCountryName = "countriesLis";

        // se traen los datos desde la DB con los que se desean crear las listas para los data validator y se rellenan los
        // arreglos que permitaran escribir los datos en el template
        List<LocElement> countryList = new ArrayList<>(locElementService.findAll().stream()
                .filter(le -> le.isActive() && (le.getLocElementType() != null)
                        && (le.getLocElementType().getId() == 2))
                .collect(Collectors.toList()));
        Collections.sort(countryList, (c1, c2) -> c1.getName().compareTo(c2.getName()));

        // arreglo usado para escribir la data de countries al template
        String[] countries = new String[countryList.size()];
        for (int i = 0; i < countryList.size(); i++) {
            countries[i] = countryList.get(i).getName() + " - " + countryList.get(i).getIsoAlpha2();
        }

        List<CapdevHighestDegree> highestDegreeList = new ArrayList<>(capdevHighestDegreeService.findAll()
                .stream().filter(h -> h.getName() != null).collect(Collectors.toList()));
        Collections.sort(highestDegreeList, (c1, c2) -> c1.getName().compareTo(c2.getName()));

        // arreglo usado para escribir la data de highest degree al template
        String[] highestDegree = new String[highestDegreeList.size()];
        for (int i = 0; i < highestDegreeList.size(); i++) {
            highestDegree[i] = highestDegreeList.get(i).getId() + "- " + highestDegreeList.get(i).getName()
                    + " (" + highestDegreeList.get(i).getAcronym() + ")";
        }

        validationHelper = sheet1.getDataValidationHelper();

        // se configuran las coordenas donde se desea pegar el data validator en la sheet1 del template
        CellRangeAddressList addressListCountry = new CellRangeAddressList(10, 1000, 3, 3);
        CellRangeAddressList addressListHighestDegree = new CellRangeAddressList(10, 1000, 4, 4);

        // se crean cada uno de los data validator
        this.createDataValidator(wb, sheet2, countries, dataValidationCountryName);

        // se configuran y pegan cada uno de los data validator
        DataValidation dataValidationCountry = this.setDataValidator(dataValidationCountryName,
                validationHelper, addressListCountry, constraintCountries);

        // set de cada data davilidator al sheet1 del template
        sheet1.addValidationData(dataValidationCountry);

        ByteArrayOutputStream fileOut = new ByteArrayOutputStream();
        wb.write(fileOut);
        wb.close();

        inputStream = new ByteArrayInputStream(fileOut.toByteArray());

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return SUCCESS;
}

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

License:Open Source License

public void createFile() throws FileNotFoundException {
    try {/*from w ww  . j  a  va2  s .  c o m*/
        DataValidation dataValidationCountries = null;
        DataValidation dataValidationInstitutions = null;
        DataValidation dataValidationCountryOfInstitutions = null;
        DataValidationConstraint constraintCountries = null;
        DataValidationConstraint constraintInstitutions = null;
        DataValidationConstraint constraintCountryOfInstitutions = null;
        DataValidationHelper validationHelper = null;

        final String path = new File(".").getCanonicalPath();
        final String filePath = "C:\\Users\\logonzalez\\Downloads\\participants-template.xlsm";
        final File file = new File(filePath);
        final FileInputStream fileInput = new FileInputStream(file);
        final XSSFWorkbook wb = new XSSFWorkbook(fileInput);

        final Sheet sheet1 = wb.getSheetAt(0);
        final XSSFSheet sheet2 = wb.getSheet("countries");
        final XSSFSheet sheet3 = wb.getSheet("institutions");

        final String reference = null;
        final String dataValidationCountryName = "countriesLis";
        final String dataValidationInstitutionName = "institutionsList";

        final String[] countries = { "1- Colombia", "2- Brazil", "3- Espenia", "4- Argentina", "5- Aruba",
                "6- Egipto", "7- Panama", "8- Ecuador" };
        final String[] institutions = { "CH- U.chile", "BZ- U.coritiba", "PN- U.panama", "AR- U.de.Palermo",
                "AF- U.delNilo", "EC- U.de.Quito", };

        for (int i = 0; i < countries.length; i++) {
            final Row fila = sheet2.createRow(i);
            final Cell celda = fila.createCell(0);
            final Cell celdaformula = fila.createCell(1);
            // final String formula = "SUM(C1,D1)";
            celda.setCellValue(countries[i]);
            // celdaformula.setCellFormula(formula);
        }

        // sheet2.protectSheet("marlo-ciat");
        // // 3. create named range for an area using AreaReference
        // final Name namedCountry = wb.createName();
        // namedCountry.setNameName(dataValidationCountryName);
        // reference = "countries!$A$1:$A$" + countries.length; // area reference
        // namedCountry.setRefersToFormula(reference);

        for (int i = 0; i < institutions.length; i++) {
            final Row fila = sheet3.createRow(i);
            final Cell celda = fila.createCell(0);
            celda.setCellValue(institutions[i]);

        }

        // final Name namedInstitution = wb.createName();
        // namedInstitution.setNameName(dataValidationInstitutionName);
        // reference = "institutions!$A$1:$A$" + institutions.length; // area reference
        // namedInstitution.setRefersToFormula(reference);
        //
        // sheet3.protectSheet("marlo-ciat");

        validationHelper = sheet1.getDataValidationHelper();
        final CellRangeAddressList addressListCountry = new CellRangeAddressList(11, 1000, 4, 4);
        constraintCountries = validationHelper.createFormulaListConstraint(dataValidationCountryName);
        dataValidationCountries = validationHelper.createValidation(constraintCountries, addressListCountry);
        dataValidationCountries.setSuppressDropDownArrow(true);
        if (dataValidationCountries instanceof XSSFDataValidation) {
            dataValidationCountries.setSuppressDropDownArrow(true);
            dataValidationCountries.setShowErrorBox(true);
        } else {
            dataValidationCountries.setSuppressDropDownArrow(false);
        }

        final CellRangeAddressList addressListInstitution = new CellRangeAddressList(11, 1000, 6, 6);
        constraintInstitutions = validationHelper.createFormulaListConstraint(dataValidationInstitutionName);
        dataValidationInstitutions = validationHelper.createValidation(constraintInstitutions,
                addressListInstitution);
        dataValidationInstitutions.setSuppressDropDownArrow(true);
        if (dataValidationInstitutions instanceof XSSFDataValidation) {
            dataValidationInstitutions.setSuppressDropDownArrow(true);
            dataValidationInstitutions.setShowErrorBox(true);
        } else {
            dataValidationInstitutions.setSuppressDropDownArrow(false);
        }

        final CellRangeAddressList addressListCountryOfInstitution = new CellRangeAddressList(11, 1000, 7, 7);
        constraintCountryOfInstitutions = validationHelper
                .createFormulaListConstraint(dataValidationCountryName);
        dataValidationCountryOfInstitutions = validationHelper.createValidation(constraintCountryOfInstitutions,
                addressListCountryOfInstitution);
        dataValidationCountryOfInstitutions.setSuppressDropDownArrow(true);
        if (dataValidationCountryOfInstitutions instanceof XSSFDataValidation) {
            dataValidationCountryOfInstitutions.setSuppressDropDownArrow(true);
            dataValidationCountryOfInstitutions.setShowErrorBox(true);
        } else {
            dataValidationCountryOfInstitutions.setSuppressDropDownArrow(false);
        }

        sheet1.addValidationData(dataValidationCountries);
        sheet1.addValidationData(dataValidationInstitutions);
        sheet1.addValidationData(dataValidationCountryOfInstitutions);

        FileOutputStream fileOut;

        fileOut = new FileOutputStream("C:\\Users\\logonzalez\\Downloads\\vineet.xlsm");
        wb.write(fileOut);
        fileOut.close();
        wb.close();

    } catch (EncryptedDocumentException | IOException e1) {
        e1.printStackTrace();
    }
}

From source file:org.excel.LinkedDropDownLists.java

License:Apache License

LinkedDropDownLists(String workbookName) {
    File file = null;/* w  w w  . ja  v a 2  s  .  co  m*/
    FileOutputStream fos = null;
    Workbook workbook = null;
    Sheet sheet = null;
    DataValidationHelper dvHelper = null;
    DataValidationConstraint dvConstraint = null;
    DataValidation validation = null;
    CellRangeAddressList addressList = null;
    try {

        // Using the ss.usermodel allows this class to support both binary
        // and xml based workbooks. The choice of which one to create is
        // made by checking the file extension.
        if (workbookName.endsWith(".xlsx")) {
            workbook = new XSSFWorkbook();
        } else {
            workbook = new HSSFWorkbook();
        }

        // Build the sheet that will hold the data for the validations. This
        // must be done first as it will create names that are referenced 
        // later.
        sheet = workbook.createSheet("Linked Validations");
        LinkedDropDownLists.buildDataSheet(sheet);

        // Build the first data validation to occupy cell A1. Note
        // that it retrieves it's data from the named area or region called
        // CHOICES. Further information about this can be found in the
        // static buildDataSheet() method below.
        addressList = new CellRangeAddressList(0, 0, 0, 0);
        dvHelper = sheet.getDataValidationHelper();
        dvConstraint = dvHelper.createFormulaListConstraint("CHOICES");
        validation = dvHelper.createValidation(dvConstraint, addressList);
        sheet.addValidationData(validation);

        // Now, build the linked or dependent drop down list that will
        // occupy cell B1. The key to the whole process is the use of the
        // INDIRECT() function. In the buildDataSheet(0 method, a series of
        // named regions are created and the names of three of them mirror
        // the options available to the user in the first drop down list
        // (in cell A1). Using the INDIRECT() function makes it possible
        // to convert the selection the user makes in that first drop down
        // into the addresses of a named region of cells and then to use
        // those cells to populate the second drop down list.
        addressList = new CellRangeAddressList(0, 0, 1, 1);
        dvConstraint = dvHelper.createFormulaListConstraint("INDIRECT(UPPER($A$1))");
        validation = dvHelper.createValidation(dvConstraint, addressList);
        sheet.addValidationData(validation);

        file = new File(workbookName);
        fos = new FileOutputStream(file);
        workbook.write(fos);
    } catch (IOException ioEx) {
        System.out.println("Caught a: " + ioEx.getClass().getName());
        System.out.println("Message: " + ioEx.getMessage());
        System.out.println("Stacktrace follws:.....");
        ioEx.printStackTrace(System.out);
    } finally {
        try {
            if (fos != null) {
                fos.close();
                fos = null;
            }
        } catch (IOException ioEx) {
            System.out.println("Caught a: " + ioEx.getClass().getName());
            System.out.println("Message: " + ioEx.getMessage());
            System.out.println("Stacktrace follws:.....");
            ioEx.printStackTrace(System.out);
        }
    }
}

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   w  ww.  ja  v  a  2  s .  c om

            //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.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  .j  a  v a 2s  .  c om*/
    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;
}