Example usage for org.apache.poi.ss.usermodel CreationHelper createRichTextString

List of usage examples for org.apache.poi.ss.usermodel CreationHelper createRichTextString

Introduction

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

Prototype

RichTextString createRichTextString(String text);

Source Link

Document

Creates a new RichTextString instance

Usage

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  a  2s  .co  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.isisaddons.module.excel.dom.CellMarshaller.java

License:Apache License

private static void setCellComment(final Cell cell, final String commentText) {
    Sheet sheet = cell.getSheet();/*  w ww. jav  a  2 s .  co m*/
    Row row = cell.getRow();
    Workbook workbook = sheet.getWorkbook();
    CreationHelper creationHelper = workbook.getCreationHelper();
    ClientAnchor anchor = creationHelper.createClientAnchor();
    anchor.setCol1(cell.getColumnIndex());
    anchor.setCol2(cell.getColumnIndex() + 1);
    anchor.setRow1(row.getRowNum());
    anchor.setRow2(row.getRowNum() + 3);

    Drawing drawing = sheet.createDrawingPatriarch();
    Comment comment1 = drawing.createCellComment(anchor);

    RichTextString commentRtf = creationHelper.createRichTextString(commentText);

    comment1.setString(commentRtf);
    Comment comment = comment1;
    cell.setCellComment(comment);
}

From source file:org.omnaest.i18nbinder.internal.XLSFile.java

License:Apache License

/**
 * Stores the data from the object onto disk.
 *//*from w w w . ja v  a2 s .c o m*/
public void store() {
    Workbook wb = this.newWorkbookToWrite();
    CreationHelper createHelper = wb.getCreationHelper();
    Sheet sheet = wb.createSheet("all");

    int lineNumber = 0;
    for (TableRow iLine : this.tableRowList) {
        //
        Row row = sheet.createRow(lineNumber++);

        //
        int cellIndex = 0;
        for (String iCellText : iLine) {
            Cell cell = row.createCell(cellIndex++);
            cell.setCellValue(createHelper.createRichTextString(iCellText));
        }
    }

    try {
        final FileOutputStream fileOutputStream = new FileOutputStream(this.file);
        final OutputStream outputStream = new BufferedOutputStream(fileOutputStream);
        wb.write(outputStream);
        outputStream.close();
        fileOutputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.onexus.website.api.widgets.download.formats.ExcelFormat.java

License:Apache License

private void writeHeader(Row header, CreationHelper helper, IEntityTable table) {

    Iterator<Map.Entry<String, List<String>>> selectIt = table.getQuery().getSelect().entrySet().iterator();
    int cell = 0;
    while (selectIt.hasNext()) {
        Map.Entry<String, List<String>> select = selectIt.next();

        ORI collectionUri = QueryUtils.getCollectionOri(table.getQuery(), select.getKey());
        Collection collection = getResourceManager().load(Collection.class, collectionUri);

        Iterator<String> fieldId = select.getValue().iterator();
        while (fieldId.hasNext()) {
            Field field = collection.getField(fieldId.next());
            if (field == null) {
                continue;
            }//from   w  w  w  .  j av  a2 s .  c o  m
            String label = field.getLabel();
            if (label == null) {
                label = field.getId();
            }
            header.createCell(cell).setCellValue(helper.createRichTextString(label));
            cell++;
        }

    }
}

From source file:org.pentaho.di.trans.steps.excelwriter.ExcelWriterStep.java

License:Apache License

private Comment createCellComment(String author, String comment) {
    // comments only supported for XLSX
    if (data.sheet instanceof XSSFSheet) {
        CreationHelper factory = data.wb.getCreationHelper();
        Drawing drawing = data.sheet.createDrawingPatriarch();

        ClientAnchor anchor = factory.createClientAnchor();
        Comment cmt = drawing.createCellComment(anchor);
        RichTextString str = factory.createRichTextString(comment);
        cmt.setString(str);//from  ww  w . j  av  a  2s. c  om
        cmt.setAuthor(author);
        return cmt;

    }
    return null;
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.table.xls.helper.ExcelTextExtractor.java

License:Open Source License

public static RichTextString computeRichText(final ExcelFontFactory fontFactory,
        final CreationHelper creationHelper, final String text, final ArrayList<RichTextFormat> buffer) {
    if (text.length() > 0) {
        if (text.length() < 32768) {
            // There's rich text.
            final RichTextString rtStr = creationHelper.createRichTextString(text);
            for (int i = 0; i < buffer.size(); i++) {
                final RichTextFormat o = buffer.get(i);
                final int position = o.getPosition();
                final HSSFFontWrapper font = o.getFont();
                if (i == (buffer.size() - 1)) {
                    // Last element ..
                    rtStr.applyFont(position, text.length(), fontFactory.getExcelFont(font));
                } else {
                    final RichTextFormat next = buffer.get(i + 1);
                    rtStr.applyFont(position, next.getPosition(), fontFactory.getExcelFont(font));
                }//ww  w.  j  a  va2 s .c  o m
            }
            return rtStr;
        } else {
            ExcelTextExtractor.logger.warn(
                    "Excel-Cells cannot contain text larger than 32.737 characters. Text will be clipped.");

            final String realText = text.substring(0, 32767);
            final RichTextString rtStr = creationHelper.createRichTextString(realText);
            for (int i = 0; i < buffer.size(); i++) {
                final RichTextFormat o = buffer.get(i);
                final int position = o.getPosition();
                if (position >= 32767) {
                    break;
                }
                final HSSFFontWrapper font = o.getFont();
                if (i == (buffer.size() - 1)) {
                    // Last element ..
                    final int endPosition = Math.min(32767, text.length());
                    rtStr.applyFont(position, endPosition, fontFactory.getExcelFont(font));
                } else {
                    final RichTextFormat next = buffer.get(i + 1);
                    final int endPosition = Math.min(32767, next.getPosition());
                    rtStr.applyFont(position, endPosition, fontFactory.getExcelFont(font));
                }
            }
            return rtStr;
        }
    }
    return null;
}

From source file:org.sakaiproject.gradebook.gwt.server.ImportExportUtilityImpl.java

License:Educational Community License

private void exportGradebookXLS(String title, OutputStream outStream, Gradebook2ComponentService service,
        String gradebookUid, final boolean includeStructure, final boolean includeComments,
        List<String> sectionUidList, boolean isXSSF) throws FatalException {

    final ImportExportDataFile file = exportGradebook(service, gradebookUid, includeStructure, includeComments,
            sectionUidList);/*from  www  .  j  a  va 2s  . c  o m*/

    Map<StructureRow, String[]> structureColumnsMap = new HashMap<StructureRow, String[]>();
    ImportExportInformation ieInfo = new ImportExportInformation();

    int structureStop = 0;

    structureStop = readDataForStructureInformation(file, buildRowIndicatorMap(), structureColumnsMap);
    if (structureStop != -1)
        readInHeaderRow(file, ieInfo, structureStop);

    int studentId = -1;
    if (ieInfo.getHeaders() != null)
        for (int i = 0; i < ieInfo.getHeaders().length; ++i) {
            if (ieInfo.getHeaders()[i] != null) {
                String thisHeaderName = ieInfo.getHeaders()[i].getValue();
                for (int j = 0; j < idColumns.length; j++) {
                    String idColumn = idColumns[j];
                    if (idColumn != null && idColumn.equalsIgnoreCase(thisHeaderName)) {
                        studentId = i;
                        break;
                    }
                }
            }
            if (studentId != -1)
                break;
        }

    org.apache.poi.ss.usermodel.Workbook wb = isXSSF ? new XSSFWorkbook() : new HSSFWorkbook();

    CreationHelper helper = wb.getCreationHelper();
    // GRBK-1086 
    org.apache.poi.ss.usermodel.Sheet s = wb.createSheet(i18n.getString("exportSheetTitle"));

    file.startReading();
    String[] curRow = null;
    int row = 0;

    Row r = null;
    while ((curRow = file.readNext()) != null) {
        r = s.createRow(row);

        for (int i = 0; i < curRow.length; i++) {
            org.apache.poi.ss.usermodel.Cell cl = r.createCell(i);
            //GRBK-840 If the cell is numeric, we should make it numeric...
            // GRBK-979 .... unless it is the student id
            if (NumberUtils.isNumber(curRow[i]) && i != studentId) {
                cl.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                cl.setCellValue(Double.valueOf(curRow[i]));
            } else {
                cl.setCellType(HSSFCell.CELL_TYPE_STRING);
                cl.setCellValue(helper.createRichTextString(curRow[i]));
            }
        }

        row++;
    }

    // Run autosize on last row's columns
    if (r != null) {
        for (int i = 0; i <= r.getLastCellNum(); i++) {
            s.autoSizeColumn((short) i);
        }
    }
    writeXLSResponse(wb, outStream);

}

From source file:org.seedstack.io.jasper.fixtures.CustomXlsRenderer.java

License:Mozilla Public License

@Override
public void render(OutputStream outputStream, Object model, String mimeType, Map<String, Object> parameters) {
    Validate.isTrue(StringUtils.equals(mimeType, "application/xls"));
    try {/*from   w  w  w.ja va2s  .c  om*/
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("new sheet");

        CreationHelper createHelper = wb.getCreationHelper();
        // Create a row and put some cells in it. Rows are 0 based.
        Row row = sheet.createRow((short) 0);

        // Or do it on one line.
        CustomerBean bean = (CustomerBean) model;
        row.createCell(1).setCellValue(bean.getCustomerNo());
        row.createCell(2).setCellValue(createHelper.createRichTextString(bean.getFirstName()));
        row.createCell(3).setCellValue(createHelper.createRichTextString(bean.getLastName()));
        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
        Cell cell = row.createCell(4);
        cell.setCellValue(bean.getBirthDate());
        cell.setCellStyle(cellStyle);
        row.createCell(5).setCellValue(bean.getMailingAddress());
        row.createCell(6).setCellValue(bean.getMarried());
        row.createCell(7).setCellValue(bean.getNumberOfKids());
        row.createCell(8).setCellValue(bean.getFavouriteQuote());
        row.createCell(9).setCellValue(bean.getEmail());
        row.createCell(10).setCellValue(bean.getLoyaltyPoints());

        wb.write(outputStream);
        outputStream.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.structr.excel.ToExcelFunction.java

License:Open Source License

public void writeToCell(final CreationHelper factory, final Drawing drawing, final XSSFCell cell,
        final Object value, final Integer maxCellLength, final String overflowMode) {

    final String cellValue = escapeForExcel(value);

    if (cellValue.length() <= maxCellLength) {

        cell.setCellValue(cellValue);/*from  w  w w.j  a  va  2s . c om*/

    } else {

        cell.setCellValue(cellValue.substring(0, maxCellLength));

        if (!overflowMode.equals("t")) {
            final Comment comment = drawing.createCellComment(factory.createClientAnchor());

            if (overflowMode.equals("o")) {
                final String overflow = cellValue.substring(maxCellLength,
                        Math.min(maxCellLength + 32767, cellValue.length()));
                comment.setString(factory.createRichTextString(overflow));
            } else {
                comment.setString(factory.createRichTextString(overflowMode));
            }

            cell.setCellComment(comment);
        }
    }
}

From source file:org.talend.dataprep.transformation.format.XlsWriter.java

License:Open Source License

@Override
public void write(RowMetadata columns) throws IOException {
    LOGGER.debug("write RowMetadata: {}", columns);
    if (columns.getColumns().isEmpty()) {
        return;/*from   w  w w.  j a v a2s . co  m*/
    }
    CreationHelper createHelper = this.workbook.getCreationHelper();
    // writing headers so first row
    Row headerRow = this.sheet.createRow(rowIdx++);
    int cellIdx = 0;
    for (ColumnMetadata columnMetadata : columns.getColumns()) {
        // TODO apply some formatting as it's an header cell?
        headerRow.createCell(cellIdx++)
                .setCellValue(createHelper.createRichTextString(columnMetadata.getName()));
    }
    // Empty buffer
    recordsWriter.flush();
    recordsWriter.close();
    try (Reader reader = new InputStreamReader(new FileInputStream(bufferFile))) {
        try (CSVReader bufferReader = new CSVReader(reader, BUFFER_CSV_SEPARATOR, '\"', '\0')) {
            String[] nextRow;
            while ((nextRow = bufferReader.readNext()) != null) {
                // writing data
                Row row = this.sheet.createRow(rowIdx++);
                cellIdx = 0;
                for (ColumnMetadata columnMetadata : columns.getColumns()) {
                    Cell cell = row.createCell(cellIdx);
                    String val = nextRow[cellIdx];
                    switch (Type.get(columnMetadata.getType())) {
                    case NUMERIC:
                    case INTEGER:
                    case DOUBLE:
                    case FLOAT:
                        try {
                            if (NumericHelper.isBigDecimal(val)) {
                                cell.setCellValue(BigDecimalParser.toBigDecimal(val).doubleValue());
                            } else {
                                cell.setCellValue(val);
                            }
                        } catch (NumberFormatException e) {
                            LOGGER.trace(
                                    "Skip NumberFormatException and use string for value '{}' row '{}' column '{}'", //
                                    val, rowIdx - 1, cellIdx - 1);
                            cell.setCellValue(val);
                        }
                        break;
                    case BOOLEAN:
                        cell.setCellValue(Boolean.valueOf(val));
                        break;
                    // FIXME ATM we don't have any idea about the date format so this can generate exceptions
                    // case "date":
                    // cell.setCellValue( );
                    default:
                        cell.setCellValue(val);
                    }
                    cellIdx++;
                }
            }
        }
    }
}