Example usage for org.apache.poi.xssf.usermodel XSSFRichTextString XSSFRichTextString

List of usage examples for org.apache.poi.xssf.usermodel XSSFRichTextString XSSFRichTextString

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFRichTextString XSSFRichTextString.

Prototype

@Internal
public XSSFRichTextString(CTRst st) 

Source Link

Document

Create a rich text string from the supplied XML bean

Usage

From source file:apm.common.utils.excel.ExportExcel.java

License:Open Source License

/**
 * ?//from  w  ww  .  j  av a  2 s.  co  m
 * @param title ?
 * @param headerList 
 */
private void initialize(String title, List<String> headerList) {
    this.wb = new SXSSFWorkbook(500);
    this.sheet = wb.createSheet("Export");
    this.styles = createStyles(wb);
    // Create title
    if (StringUtils.isNotBlank(title)) {
        Row titleRow = sheet.createRow(rownum++);
        titleRow.setHeightInPoints(30);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellStyle(styles.get("title"));
        titleCell.setCellValue(title);
        sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(),
                titleRow.getRowNum(), headerList.size() - 1));
    }
    // Create header
    if (headerList == null) {
        throw new RuntimeException("headerList not null!");
    }
    Row headerRow = sheet.createRow(rownum++);
    headerRow.setHeightInPoints(16);
    for (int i = 0; i < headerList.size(); i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellStyle(styles.get("header"));
        String[] ss = StringUtils.split(headerList.get(i), "**", 2);
        if (ss.length == 2) {
            cell.setCellValue(ss[0]);
            Comment comment = this.sheet.createDrawingPatriarch()
                    .createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
            comment.setString(new XSSFRichTextString(ss[1]));
            cell.setCellComment(comment);
        } else {
            cell.setCellValue(headerList.get(i));
        }
        sheet.autoSizeColumn(i);
    }
    for (int i = 0; i < headerList.size(); i++) {
        int colWidth = sheet.getColumnWidth(i) * 2;
        sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
    }
    log.debug("Initialize success.");
}

From source file:beans.utilidades.MetodosGenerales.java

public void createCell(XSSFCellStyle cellStyle, XSSFRow fila, int position, String value) {
    XSSFCell cell;//from  w w w  . j a  v a 2 s.c o m
    cell = fila.createCell((short) position);// Se crea una cell dentro de la fila                        
    cell.setCellValue(new XSSFRichTextString(value));
    cell.setCellStyle(cellStyle);
}

From source file:beans.utilidades.MetodosGenerales.java

public void createCell(XSSFRow fila, int position, String value) {
    XSSFCell cell;/*w w  w.  ja  v a2 s . c o  m*/
    cell = fila.createCell((short) position);// Se crea una cell dentro de la fila                        
    cell.setCellValue(new XSSFRichTextString(value));
}

From source file:cn.afterturn.easypoi.excel.export.base.BaseExportService.java

License:Apache License

/**
 * Cell/*from  w  w  w.  j  a va  2  s  .co  m*/
 */
public void createStringCell(Row row, int index, String text, CellStyle style, ExcelExportEntity entity) {
    Cell cell = row.createCell(index);
    if (style != null && style.getDataFormat() > 0 && style.getDataFormat() < 12) {
        cell.setCellValue(Double.parseDouble(text));
        cell.setCellType(CellType.NUMERIC);
    } else {
        RichTextString rtext;
        if (type.equals(ExcelType.HSSF)) {
            rtext = new HSSFRichTextString(text);
        } else {
            rtext = new XSSFRichTextString(text);
        }
        cell.setCellValue(rtext);
    }
    if (style != null) {
        cell.setCellStyle(style);
    }
    addStatisticsData(index, text, entity);
}

From source file:cn.bzvs.excel.export.base.ExcelExportBase.java

License:Apache License

/**
 * Cell/*from ww  w  .  ja v a2s  . c o  m*/
 *
 * @param row
 * @param index
 * @param text
 * @param style
 * @param entity
 */
public void createStringCell(Row row, int index, String text, CellStyle style, ExcelExportEntity entity) {
    Cell cell = row.createCell(index);
    if (style != null && style.getDataFormat() > 0 && style.getDataFormat() < 12) {
        cell.setCellValue(Double.parseDouble(text));
        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
    } else {
        RichTextString Rtext;
        if (type.equals(ExcelType.HSSF)) {
            Rtext = new HSSFRichTextString(text);
        } else {
            Rtext = new XSSFRichTextString(text);
        }
        cell.setCellValue(Rtext);
    }
    if (style != null) {
        cell.setCellStyle(style);
    }
    addStatisticsData(index, text, entity);
}

From source file:cn.bzvs.excel.imports.sax.SheetHandler.java

License:Apache License

@Override
public void endElement(String uri, String localName, String name) throws SAXException {

    // ?SST??  /*  w w w. j a va 2  s .co m*/
    // characters()?  
    if (CellValueType.String.equals(type)) {
        try {
            int idx = Integer.parseInt(lastContents);
            lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
        } catch (Exception e) {

        }
    }
    //t?  
    if (CellValueType.TElement.equals(type)) {
        String value = lastContents.trim();
        rowlist.add(curCol, new SaxReadCellEntity(CellValueType.String, value));
        curCol++;
        type = CellValueType.None;
        // v => ??vSST  
        // ?rowlist???  
    } else if ("v".equals(name)) {
        String value = lastContents.trim();
        value = value.equals("") ? " " : value;
        if (CellValueType.Date.equals(type)) {
            Date date = HSSFDateUtil.getJavaDate(Double.valueOf(value));
            rowlist.add(curCol, new SaxReadCellEntity(CellValueType.Date, date));
        } else if (CellValueType.Number.equals(type)) {
            BigDecimal bd = new BigDecimal(value);
            rowlist.add(curCol, new SaxReadCellEntity(CellValueType.Number, bd));
        } else if (CellValueType.String.equals(type)) {
            rowlist.add(curCol, new SaxReadCellEntity(CellValueType.String, value));
        }
        curCol++;
    } else if (name.equals("row")) {//?? row  optRows()   
        read.parse(curRow, rowlist);
        rowlist.clear();
        curRow++;
        curCol = 0;
    }

}

From source file:com.adanac.excel.reader.sax.ExcelXSSFSheetXMLHandler.java

License:Apache License

@Override
public void endElement(String uri, String localName, String name) throws SAXException {
    String thisStr = null;// w  w  w.j a v  a 2  s  .  c o  m

    // v => contents of a cell
    if (isTextTag(name)) {
        vIsOpen = false;

        // Process the value contents as required, now we have it all
        switch (nextDataType) {
        case BOOLEAN:
            char first = value.charAt(0);
            thisStr = first == '0' ? "FALSE" : "TRUE";
            break;

        case ERROR:
            thisStr = "ERROR:" + value.toString();
            break;

        case FORMULA:
            if (formulasNotResults) {
                thisStr = formula.toString();
            } else {
                String fv = value.toString();

                if (this.formatString != null) {
                    try {
                        // Try to use the value as a formattable number
                        double d = Double.parseDouble(fv);
                        thisStr = formatter.formatRawCellContents(d, this.formatIndex, this.formatString);
                    } catch (NumberFormatException e) {
                        // Formula is a String result not a Numeric one
                        thisStr = fv;
                    }
                } else {
                    // No formating applied, just do raw value in all cases
                    thisStr = fv;
                }
            }
            break;

        case INLINE_STRING:
            // TODO: Can these ever have formatting on them?
            XSSFRichTextString rtsi = new XSSFRichTextString(value.toString());
            thisStr = rtsi.toString();
            break;

        case SST_STRING:
            String sstIndex = value.toString();
            try {
                int idx = Integer.parseInt(sstIndex);
                XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx));
                thisStr = rtss.toString();
            } catch (NumberFormatException ex) {
                logger.log(POILogger.ERROR, "Failed to parse SST index '" + sstIndex, ex);
            }
            break;

        case NUMBER:
            String n = value.toString();
            if (this.formatString != null && n.length() > 0)
                thisStr = formatter.formatRawCellContents(Double.parseDouble(n), this.formatIndex,
                        this.formatString);
            else
                thisStr = n;
            break;

        default:
            thisStr = "(TODO: Unexpected type: " + nextDataType + ")";
            break;
        }

        // Do we have a comment for this cell? 
        //checkForEmptyCellComments(EmptyCellCommentsCheckType.CELL);
        XSSFComment comment = commentsTable != null ? commentsTable.findCellComment(cellRef) : null;

        // Output ??
        output.cell(rowNum, cellRef, thisStr, comment);
    } else if ("f".equals(name)) {
        fIsOpen = false;
    } else if ("is".equals(name)) {
        isIsOpen = false;
    } else if ("row".equals(name)) {
        // Handle any "missing" cells which had comments attached
        checkForEmptyCellComments(EmptyCellCommentsCheckType.END_OF_ROW);

        // Finish up the row
        output.endRow(rowNum);

        // some sheets do not have rowNum set in the XML, Excel can read
        // them so we should try to read them as well
        nextRowNum = rowNum + 1;
    } else if ("sheetData".equals(name)) {
        // Handle any "missing" cells which had comments attached
        checkForEmptyCellComments(EmptyCellCommentsCheckType.END_OF_SHEET_DATA);
    } else if ("oddHeader".equals(name) || "evenHeader".equals(name) || "firstHeader".equals(name)) {
        hfIsOpen = false;
        output.headerFooter(headerFooter.toString(), true, name);
    } else if ("oddFooter".equals(name) || "evenFooter".equals(name) || "firstFooter".equals(name)) {
        hfIsOpen = false;
        output.headerFooter(headerFooter.toString(), false, name);
    }
}

From source file:com.cisco.ca.cstg.pdi.utils.Util.java

public static void json2Excel(OutputStream output, String json, String[] properties, String[] columnsNames)
        throws IOException {
    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet();
    Row header = sheet.createRow(0);/* www. j  av a 2s .co m*/

    for (int i = 0; i < columnsNames.length; i++) {
        String string = columnsNames[i];
        Cell cell = header.createCell(i);
        RichTextString text = new XSSFRichTextString(string);
        cell.setCellValue(text);
    }

    LOGGER.info("Writing on workbook.");
    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(json);

        int i = 0;
        for (JsonNode jsonNode2 : jsonNode) {
            Row row = sheet.createRow(++i);

            for (int j = 0; j < properties.length; j++) {
                String string = properties[j];
                Cell cell = row.createCell(j);
                RichTextString text = new XSSFRichTextString(jsonNode2.get(string).getTextValue());
                cell.setCellValue(text);
            }
        }
    } catch (JsonProcessingException e) {
        LOGGER.error(e.getMessage(), e);
    }

    workbook.write(output);
    workbook.close();
    LOGGER.info("Written on workbook.");
}

From source file:com.crm.webapp.util.ExcelCustomExporter.java

License:Apache License

@Override
public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle,
        boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor, boolean subTable) throws IOException {

    wb = new XSSFWorkbook();
    String safeName = WorkbookUtil.createSafeSheetName(filename);
    Sheet sheet = wb.createSheet(safeName);

    cellStyle = wb.createCellStyle();/*from w w  w  . ja va2  s.  c  om*/
    facetStyle = wb.createCellStyle();
    titleStyle = wb.createCellStyle();
    createCustomFonts();

    int maxColumns = 0;
    StringTokenizer st = new StringTokenizer(tableId, ",");
    while (st.hasMoreElements()) {
        String tableName = (String) st.nextElement();
        UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(),
                tableName);
        if (component == null) {
            throw new FacesException("Cannot find component \"" + tableName + "\" in view.");
        }
        if (!(component instanceof DataTable || component instanceof DataList)) {
            throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName()
                    + "\", exporter must target a PrimeFaces DataTable/DataList.");
        }

        DataList list = null;
        DataTable table = null;
        int cols = 0;
        if (preProcessor != null) {
            preProcessor.invoke(context.getELContext(), new Object[] { wb });
        }
        if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) {
            Row titleRow = sheet.createRow(sheet.getLastRowNum());
            int cellIndex = titleRow.getLastCellNum() == -1 ? 0 : titleRow.getLastCellNum();
            Cell cell = titleRow.createCell(cellIndex);
            cell.setCellValue(new XSSFRichTextString(tableTitle));
            Font titleFont = wb.createFont();
            titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
            titleStyle.setFont(titleFont);
            cell.setCellStyle(titleStyle);
            sheet.createRow(sheet.getLastRowNum() + 3);

        }
        if (component instanceof DataList) {
            list = (DataList) component;

            if (list.getHeader() != null) {
                tableFacet(context, sheet, list, "header");
            }
            if (pageOnly) {
                exportPageOnly(context, list, sheet);
            } else {
                exportAll(context, list, sheet);
            }
            cols = list.getRowCount();
        } else {

            table = (DataTable) component;
            int columnsCount = getColumnsCount(table);

            if (table.getHeader() != null && !subTable) {
                tableFacet(context, sheet, table, columnsCount, "header");

            }
            if (!subTable) {
                tableColumnGroup(sheet, table, "header");
            }

            addColumnFacets(table, sheet, ColumnType.HEADER);

            if (pageOnly) {
                exportPageOnly(context, table, sheet);
            } else if (selectionOnly) {
                exportSelectionOnly(context, table, sheet);
            } else {
                exportAll(context, table, sheet, subTable);
            }

            if (table.hasFooterColumn() && !subTable) {
                addColumnFacets(table, sheet, ColumnType.FOOTER);
            }
            if (!subTable) {
                tableColumnGroup(sheet, table, "footer");
            }
            table.setRowIndex(-1);
            if (postProcessor != null) {
                postProcessor.invoke(context.getELContext(), new Object[] { wb });
            }
            cols = table.getColumnsCount();

            if (maxColumns < cols) {
                maxColumns = cols;
            }
        }
        sheet.createRow(sheet.getLastRowNum() + Integer.parseInt(datasetPadding));
    }

    if (!subTable)
        for (int i = 0; i < maxColumns; i++) {
            sheet.autoSizeColumn((short) i);
        }

    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    printSetup.setPaperSize(PrintSetup.A4_PAPERSIZE);
    sheet.setPrintGridlines(true);

    writeExcelToResponse(context.getExternalContext(), wb, filename);

}

From source file:com.crm.webapp.util.ExcelCustomExporter.java

License:Apache License

protected void exportCells(DataTable table, Sheet sheet, int rowIndex) {
    int sheetRowIndex = sheet.getLastRowNum() + 1;
    Row row = sheet.createRow(sheetRowIndex);

    for (UIColumn col : table.getColumns()) {
        if (!col.isRendered()) {
            continue;
        }//from w  w w .j a v a2  s.c om

        if (col instanceof DynamicColumn) {
            ((DynamicColumn) col).applyModel();
        }

        if (col.isExportable()) {
            //Adding RowIndex for custom Export
            UIComponent component = (UIComponent) col;
            if (component.getId().equalsIgnoreCase("subject")) {

                Cell cell = row.createCell(0);
                String value = rowIndex + "";
                cell.setCellValue(new XSSFRichTextString(value));
            }
            addColumnValue(row, col.getChildren(), "content");
        }
    }
    FacesContext context = null;
    if (table.getRowIndex() == 0) {
        for (UIComponent component : table.getChildren()) {
            if (component instanceof RowExpansion) {
                RowExpansion rowExpansion = (RowExpansion) component;
                if (rowExpansion.getChildren() != null) {
                    if (rowExpansion.getChildren().get(0) instanceof DataTable) {
                        DataTable childTable = (DataTable) rowExpansion.getChildren().get(0);
                        childTable.setRowIndex(-1);
                    }
                    if (rowExpansion.getChildren().get(0) instanceof DataList) {
                        DataList childList = (DataList) rowExpansion.getChildren().get(0);
                        childList.setRowIndex(-1);
                    }
                }

            }
        }
    }
    table.setRowIndex(table.getRowIndex() + 1);
    for (UIComponent component : table.getChildren()) {
        if (component instanceof RowExpansion) {
            RowExpansion rowExpansion = (RowExpansion) component;
            if (rowExpansion.getChildren() != null) {
                if (rowExpansion.getChildren().get(0) instanceof DataList) {
                    DataList list = (DataList) rowExpansion.getChildren().get(0);
                    if (list.getHeader() != null) {
                        tableFacet(context, sheet, list, "header");
                    }
                    exportAll(context, list, sheet);
                }
                if (rowExpansion.getChildren().get(0) instanceof DataTable) {
                    DataTable childTable = (DataTable) rowExpansion.getChildren().get(0);
                    int columnsCount = getColumnsCount(childTable);

                    if (childTable.getHeader() != null) {
                        tableFacet(context, sheet, childTable, columnsCount, "header");

                    }
                    tableColumnGroup(sheet, childTable, "header");

                    addColumnFacets(childTable, sheet, ColumnType.HEADER);

                    exportAll(context, childTable, sheet, false);

                    if (childTable.hasFooterColumn()) {
                        addColumnFacets(childTable, sheet, ColumnType.FOOTER);
                    }
                    tableColumnGroup(sheet, childTable, "footer");
                    childTable.setRowIndex(-1);
                }

            }
        }
    }
}