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

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

Introduction

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

Prototype

void setHyperlink(Hyperlink link);

Source Link

Document

Assign a hyperlink to this cell

Usage

From source file:org.joeffice.spreadsheet.cell.CellUtils.java

License:Apache License

public static void copyCell(Cell oldCell, Cell newCell) {
    newCell.setCellStyle(oldCell.getCellStyle());

    if (newCell.getCellComment() != null) {
        newCell.setCellComment(oldCell.getCellComment());
    }/*from   www .  j a v  a  2  s  .c o  m*/

    if (oldCell.getHyperlink() != null) {
        newCell.setHyperlink(oldCell.getHyperlink());
    }

    newCell.setCellType(oldCell.getCellType());

    // Set the cell data value
    switch (oldCell.getCellType()) {
    case Cell.CELL_TYPE_BLANK:
        break;
    case Cell.CELL_TYPE_BOOLEAN:
        newCell.setCellValue(oldCell.getBooleanCellValue());
        break;
    case Cell.CELL_TYPE_ERROR:
        newCell.setCellErrorValue(oldCell.getErrorCellValue());
        break;
    case Cell.CELL_TYPE_FORMULA:
        newCell.setCellFormula(oldCell.getCellFormula());
        break;
    case Cell.CELL_TYPE_NUMERIC:
        newCell.setCellValue(oldCell.getNumericCellValue());
        break;
    case Cell.CELL_TYPE_STRING:
        newCell.setCellValue(oldCell.getRichStringCellValue());
        break;
    }
}

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

License:Apache License

void writeField(Object v, ValueMetaInterface vMeta, ExcelWriterStepField excelField, Row xlsRow, int posX,
        Object[] row, int fieldNr, boolean isTitle) throws KettleException {
    try {/*from  w  w w. j  av a2s  . co m*/
        boolean cellExisted = true;
        // get the cell
        Cell cell = xlsRow.getCell(posX);
        if (cell == null) {
            cellExisted = false;
            cell = xlsRow.createCell(posX);
        }

        // if cell existed and existing cell's styles should not be changed, don't
        if (!(cellExisted && meta.isLeaveExistingStylesUnchanged())) {

            // if the style of this field is cached, reuse it
            if (!isTitle && data.getCachedStyle(fieldNr) != null) {
                cell.setCellStyle(data.getCachedStyle(fieldNr));
            } else {
                // apply style if requested
                if (excelField != null) {

                    // determine correct cell for title or data rows
                    String styleRef = null;
                    if (!isTitle && !Utils.isEmpty(excelField.getStyleCell())) {
                        styleRef = excelField.getStyleCell();
                    } else if (isTitle && !Utils.isEmpty(excelField.getTitleStyleCell())) {
                        styleRef = excelField.getTitleStyleCell();
                    }

                    if (styleRef != null) {
                        Cell styleCell = getCellFromReference(styleRef);
                        if (styleCell != null && cell != styleCell) {
                            cell.setCellStyle(styleCell.getCellStyle());
                        }
                    }
                }

                // set cell format as specified, specific format overrides cell specification
                if (!isTitle && excelField != null && !Utils.isEmpty(excelField.getFormat())
                        && !excelField.getFormat().startsWith("Image")) {
                    setDataFormat(excelField.getFormat(), cell);
                }
                // cache it for later runs
                if (!isTitle) {
                    data.cacheStyle(fieldNr, cell.getCellStyle());
                }
            }
        }

        // create link on cell if requested
        if (!isTitle && excelField != null && data.linkfieldnrs[fieldNr] >= 0) {
            String link = data.inputRowMeta.getValueMeta(data.linkfieldnrs[fieldNr])
                    .getString(row[data.linkfieldnrs[fieldNr]]);
            if (!Utils.isEmpty(link)) {
                CreationHelper ch = data.wb.getCreationHelper();
                // set the link on the cell depending on link type
                Hyperlink hyperLink = null;
                if (link.startsWith("http:") || link.startsWith("https:") || link.startsWith("ftp:")) {
                    hyperLink = ch.createHyperlink(HyperlinkType.URL);
                    hyperLink.setLabel("URL Link");
                } else if (link.startsWith("mailto:")) {
                    hyperLink = ch.createHyperlink(HyperlinkType.EMAIL);
                    hyperLink.setLabel("Email Link");
                } else if (link.startsWith("'")) {
                    hyperLink = ch.createHyperlink(HyperlinkType.DOCUMENT);
                    hyperLink.setLabel("Link within this document");
                } else {
                    hyperLink = ch.createHyperlink(HyperlinkType.FILE);
                    hyperLink.setLabel("Link to a file");
                }

                hyperLink.setAddress(link);
                cell.setHyperlink(hyperLink);

                // if cell existed and existing cell's styles should not be changed, don't
                if (!(cellExisted && meta.isLeaveExistingStylesUnchanged())) {

                    if (data.getCachedLinkStyle(fieldNr) != null) {
                        cell.setCellStyle(data.getCachedLinkStyle(fieldNr));
                    } else {
                        // CellStyle style = cell.getCellStyle();
                        Font origFont = data.wb.getFontAt(cell.getCellStyle().getFontIndex());
                        Font hlink_font = data.wb.createFont();
                        // reporduce original font characteristics

                        hlink_font.setBold(origFont.getBold());
                        hlink_font.setCharSet(origFont.getCharSet());
                        hlink_font.setFontHeight(origFont.getFontHeight());
                        hlink_font.setFontName(origFont.getFontName());
                        hlink_font.setItalic(origFont.getItalic());
                        hlink_font.setStrikeout(origFont.getStrikeout());
                        hlink_font.setTypeOffset(origFont.getTypeOffset());
                        // make it blue and underlined
                        hlink_font.setUnderline(Font.U_SINGLE);
                        hlink_font.setColor(IndexedColors.BLUE.getIndex());
                        CellStyle style = cell.getCellStyle();
                        style.setFont(hlink_font);
                        cell.setCellStyle(style);
                        data.cacheLinkStyle(fieldNr, cell.getCellStyle());
                    }
                }
            }
        }

        // create comment on cell if requrested
        if (!isTitle && excelField != null && data.commentfieldnrs[fieldNr] >= 0
                && data.wb instanceof XSSFWorkbook) {
            String comment = data.inputRowMeta.getValueMeta(data.commentfieldnrs[fieldNr])
                    .getString(row[data.commentfieldnrs[fieldNr]]);
            if (!Utils.isEmpty(comment)) {
                String author = data.commentauthorfieldnrs[fieldNr] >= 0
                        ? data.inputRowMeta.getValueMeta(data.commentauthorfieldnrs[fieldNr]).getString(
                                row[data.commentauthorfieldnrs[fieldNr]])
                        : "Kettle PDI";
                cell.setCellComment(createCellComment(author, comment));
            }
        }
        // cell is getting a formula value or static content
        if (!isTitle && excelField != null && excelField.isFormula()) {
            // formula case
            cell.setCellFormula(vMeta.getString(v));
        } else {
            // static content case
            switch (vMeta.getType()) {
            case ValueMetaInterface.TYPE_DATE:
                if (v != null && vMeta.getDate(v) != null) {
                    cell.setCellValue(vMeta.getDate(v));
                }
                break;
            case ValueMetaInterface.TYPE_BOOLEAN:
                if (v != null) {
                    cell.setCellValue(vMeta.getBoolean(v));
                }
                break;
            case ValueMetaInterface.TYPE_STRING:
            case ValueMetaInterface.TYPE_BINARY:
                if (v != null) {
                    cell.setCellValue(vMeta.getString(v));
                }
                break;
            case ValueMetaInterface.TYPE_BIGNUMBER:
            case ValueMetaInterface.TYPE_NUMBER:
            case ValueMetaInterface.TYPE_INTEGER:
                if (v != null) {
                    cell.setCellValue(vMeta.getNumber(v));
                }
                break;
            default:
                break;
            }
        }
    } catch (Exception e) {
        logError("Error writing field (" + data.posX + "," + data.posY + ") : " + e.toString());
        logError(Const.getStackTracker(e));
        throw new KettleException(e);
    }
}

From source file:org.projectforge.excel.ExportSheet.java

License:Open Source License

private static Row copyRow(Sheet worksheet, int rowNum) {
    Row sourceRow = worksheet.getRow(rowNum);

    //Save the text of any formula before they are altered by row shifting
    String[] formulasArray = new String[sourceRow.getLastCellNum()];
    for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
        if (sourceRow.getCell(i) != null && sourceRow.getCell(i).getCellType() == Cell.CELL_TYPE_FORMULA)
            formulasArray[i] = sourceRow.getCell(i).getCellFormula();
    }/* w w  w. j  a va  2s  .c om*/

    worksheet.shiftRows(rowNum, worksheet.getLastRowNum(), 1);
    Row newRow = sourceRow; //Now sourceRow is the empty line, so let's rename it
    sourceRow = worksheet.getRow(rowNum + 1); //Now the source row is at rowNum+1

    // Loop through source columns to add to new row
    for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
        // Grab a copy of the old/new cell
        Cell oldCell = sourceRow.getCell(i);
        Cell newCell;

        // If the old cell is null jump to next cell
        if (oldCell == null) {
            continue;
        } else {
            newCell = newRow.createCell(i);
        }

        // Copy style from old cell and apply to new cell
        CellStyle newCellStyle = worksheet.getWorkbook().createCellStyle();
        newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
        newCell.setCellStyle(newCellStyle);

        // If there is a cell comment, copy
        if (oldCell.getCellComment() != null) {
            newCell.setCellComment(oldCell.getCellComment());
        }

        // If there is a cell hyperlink, copy
        if (oldCell.getHyperlink() != null) {
            newCell.setHyperlink(oldCell.getHyperlink());
        }

        // Set the cell data type
        newCell.setCellType(oldCell.getCellType());

        // Set the cell data value
        switch (oldCell.getCellType()) {
        case Cell.CELL_TYPE_BLANK:
            break;
        case Cell.CELL_TYPE_BOOLEAN:
            newCell.setCellValue(oldCell.getBooleanCellValue());
            break;
        case Cell.CELL_TYPE_ERROR:
            newCell.setCellErrorValue(oldCell.getErrorCellValue());
            break;
        case Cell.CELL_TYPE_FORMULA:
            newCell.setCellFormula(formulasArray[i]);
            break;
        case Cell.CELL_TYPE_NUMERIC:
            newCell.setCellValue(oldCell.getNumericCellValue());
            break;
        case Cell.CELL_TYPE_STRING:
            newCell.setCellValue(oldCell.getRichStringCellValue());
            break;
        default:
            break;
        }
    }

    // If there are any merged regions in the source row, copy to new row
    for (int i = 0; i < worksheet.getNumMergedRegions(); i++) {
        CellRangeAddress cellRangeAddress = worksheet.getMergedRegion(i);
        if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum()) {
            CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.getRowNum(),
                    (newRow.getRowNum() + (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow())),
                    cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn());
            worksheet.addMergedRegion(newCellRangeAddress);
        }
    }
    return newRow;
}

From source file:org.sakaiproject.signup.tool.downloadEvents.EventWorksheet.java

License:Educational Community License

/**
 * Create a short version excel worksheet
 *//*ww w  .  ja  va2s  .co m*/
private Workbook createShortVersonWorksheet(List<SignupMeetingWrapper> wrappers) {

    String eventTitle = rb.getString("event_overview", "Events Overview");
    Sheet sheet = wb.createSheet(eventTitle);
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);

    sheet.setColumnWidth(0, 20 * 256);
    sheet.setColumnWidth(1, 15 * 256);
    sheet.setColumnWidth(2, 16 * 256);
    sheet.setColumnWidth(3, 15 * 256);
    sheet.setColumnWidth(4, 25 * 256);
    sheet.setColumnWidth(5, 19 * 256);

    // title row
    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(35);
    for (int i = 0; i <= 6; i++) {
        titleRow.createCell(i).setCellStyle(styles.get("title"));
    }
    Cell titleCell = titleRow.getCell(0);
    titleCell.setCellValue(eventTitle);
    sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$F$1"));

    // Cureent viewer row
    Row row = sheet.createRow(2);
    row.setHeightInPoints(rowHigh);
    Cell cell = row.createCell(0);
    cell.setCellValue(rb.getString("event_viewer", "Viewer:"));
    cell.setCellStyle(styles.get("item_leftBold"));
    cell = row.createCell(1);
    cell.setCellStyle(styles.get("item_left"));
    cell.setCellValue(getCurrentUserName());

    // site title row
    row = sheet.createRow(3);
    row.setHeightInPoints(rowHigh);
    cell = row.createCell(0);
    cell.setCellValue(rb.getString("event_site_title", "Site Title:"));
    cell.setCellStyle(styles.get("item_leftBold"));
    cell = row.createCell(1);
    cell.setCellStyle(styles.get("item_left"));
    cell.setCellValue(getCurrentSiteTitle());

    // Table titles th row
    row = sheet.createRow(5);
    row.setHeightInPoints(rowHigh);
    for (int i = 0; i <= 6; i++) {
        row.createCell(i).setCellStyle(styles.get("tabColNames"));
    }
    cell = row.getCell(0);
    cell.setCellValue(tabTitles_shortVersion[0]);
    cell = row.getCell(1);
    cell.setCellValue(tabTitles_shortVersion[1]);
    cell = row.getCell(2);
    cell.setCellValue(tabTitles_shortVersion[2]);
    cell = row.getCell(3);
    cell.setCellValue(tabTitles_shortVersion[3]);
    cell = row.getCell(4);
    cell.setCellValue(tabTitles_shortVersion[4]);
    cell = row.getCell(5);
    cell.setCellValue(tabTitles_shortVersion[5]);
    cell = row.getCell(6);
    cell.setCellValue(tabTitles_shortVersion[6]);

    /* table row data */
    int rowNum = 6;
    int seqNum = 1;
    for (SignupMeetingWrapper wrp : wrappers) {
        if (wrp.isToDownload()) {
            row = sheet.createRow(rowNum);
            int rowHighNum = 1;
            rowNum++;
            for (int i = 0; i <= 6; i++) {
                row.createCell(i).setCellStyle(styles.get("tabItem_fields"));
            }
            // event ttile
            cell = row.getCell(0);
            cell.setCellStyle(styles.get("item_left_wrap"));
            cell.setCellValue(wrp.getMeeting().getTitle());
            Hyperlink sheetLink = createHelper.createHyperlink(Hyperlink.LINK_DOCUMENT);
            String validSheetName = CreateValidWorksheetName(wrp.getMeeting().getTitle(), seqNum, true);
            String hlinkAddr = "'" + validSheetName + "'" + "!A1";
            sheetLink.setAddress(hlinkAddr);
            cell.setHyperlink(sheetLink);
            cell.setCellStyle(styles.get("hyperLink"));
            seqNum++;

            // event owner
            cell = row.getCell(1);
            cell.setCellValue(wrp.getCreator());

            // event location
            cell = row.getCell(2);
            cell.setCellValue(wrp.getMeeting().getLocation());

            // event category
            cell = row.getCell(3);
            cell.setCellValue(wrp.getMeeting().getCategory());

            // event Date
            cell = row.getCell(4);
            cell.setCellValue(getShortWeekDayName(wrp.getStartTime()) + ", "
                    + getTime(wrp.getStartTime()).toStringLocalShortDate());

            // event time period
            cell = row.getCell(5);
            cell.setCellValue(getMeetingPeriodShortVersion(wrp));

            // event status
            cell = row.getCell(6);
            cell.setCellValue(
                    ExcelPlainTextFormat.convertFormattedHtmlTextToExcelPlaintext(wrp.getAvailableStatus()));
        }
    }

    // end of table line
    row = sheet.createRow(rowNum);
    for (int i = 0; i <= 6; i++) {
        row.createCell(i).setCellStyle(styles.get("tab_endline"));
    }

    return wb;
}

From source file:org.sakaiproject.signup.tool.downloadEvents.EventWorksheet.java

License:Educational Community License

/**
 * Create a full version excel worksheet
 *//*from www.j  av  a 2  s.  com*/
private void createWorksheet(SignupMeetingWrapper wrapper, int serialNum, boolean hasSerialNum) {
    String validSheetName = CreateValidWorksheetName(wrapper.getMeeting().getTitle(), serialNum, hasSerialNum);

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

    sheet.setColumnWidth(0, 3 * 256);
    sheet.setColumnWidth(1, 3 * 256);
    sheet.setColumnWidth(2, 17 * 256);
    sheet.setColumnWidth(3, 15 * 256);
    sheet.setColumnWidth(4, 22 * 256);
    sheet.setColumnWidth(5, 22 * 256);
    sheet.setColumnWidth(6, 22 * 256);

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

    // timezone row
    Row timezoneRow = sheet.createRow(1);
    timezoneRow.setHeightInPoints(16);
    for (int i = 1; i <= 7; i++) {
        timezoneRow.createCell(i).setCellStyle(styles.get("tabItem_fields"));
    }
    Cell timezoneCell = timezoneRow.getCell(2);
    timezoneCell.setCellValue("(" + rb.getString("event_timezone") + " "
            + sakaiFacade.getTimeService().getLocalTimeZone().getID() + ")");
    sheet.addMergedRegion(CellRangeAddress.valueOf("$C$2:$H$2"));

    // owner row
    Row row = sheet.createRow(2);
    row.setHeightInPoints(rowHigh);
    Cell cell = row.createCell(2);
    cell.setCellValue(rb.getString("event_owner"));
    cell.setCellStyle(styles.get("item_leftBold"));
    cell = row.createCell(3);
    cell.setCellStyle(styles.get("item_left"));
    cell.setCellValue(wrapper.getCreator());

    // meeting Date row
    row = sheet.createRow(3);
    row.setHeightInPoints(rowHigh);
    cell = row.createCell(2);
    cell.setCellValue(rb.getString("event_date"));
    cell.setCellStyle(styles.get("item_leftBold"));
    cell = row.createCell(3);
    cell.setCellStyle(styles.get("item_left"));
    cell.setCellValue(getTime(wrapper.getStartTime()).toStringLocalDate());

    // Time Period row
    row = sheet.createRow(4);
    row.setHeightInPoints(rowHigh);
    cell = row.createCell(2);
    cell.setCellValue(rb.getString("event_time_period"));
    cell.setCellStyle(styles.get("item_leftBold"));
    cell = row.createCell(3);
    cell.setCellStyle(styles.get("item_left"));
    cell.setCellValue(getMeetingPeriod(wrapper.getMeeting()));

    // Sign-up Begins row
    row = sheet.createRow(5);
    row.setHeightInPoints(rowHigh);
    cell = row.createCell(2);
    cell.setCellValue(rb.getString("event_signup_start"));
    cell.setCellStyle(styles.get("item_leftBold"));
    cell = row.createCell(3);
    cell.setCellStyle(styles.get("item_left"));
    cell.setCellValue(getTime(wrapper.getMeeting().getSignupBegins()).toStringLocalDate() + ", "
            + getTime(wrapper.getMeeting().getSignupBegins()).toStringLocalTime());

    // Sign-up Ends row
    row = sheet.createRow(6);
    row.setHeightInPoints(rowHigh);
    cell = row.createCell(2);
    cell.setCellValue(rb.getString("event_signup_deadline"));
    cell.setCellStyle(styles.get("item_leftBold"));
    cell = row.createCell(3);
    cell.setCellStyle(styles.get("item_left"));
    cell.setCellValue(getTime(wrapper.getMeeting().getSignupDeadline()).toStringLocalDate() + ", "
            + getTime(wrapper.getMeeting().getSignupDeadline()).toStringLocalTime());

    // Available To row
    row = sheet.createRow(7);
    for (int i = 1; i <= 5; i++) {
        row.createCell(i);
    }
    cell = row.getCell(2);
    cell.setCellValue(rb.getString("event_publish_to"));
    cell.setCellStyle(styles.get("item_leftBold"));
    cell = row.getCell(3);
    cell.setCellStyle(styles.get("item_left_wrap"));
    String availSitesGroups = getAvailableSitesGroups(wrapper.getMeeting());
    cell.setCellValue(availSitesGroups);
    int rownum = getNumRows(availSitesGroups);
    row.setHeightInPoints(rowHigh * rownum);
    sheet.addMergedRegion(CellRangeAddress.valueOf("$D$8:$F$8"));

    // Description row
    row = sheet.createRow(8);
    for (int i = 1; i <= 7; i++) {
        row.createCell(i);// setCellStyle(styles.get("description"));
    }
    // cell = row.createCell(2);
    cell = row.getCell(2);
    cell.setCellValue(rb.getString("event_description"));
    cell.setCellStyle(styles.get("item_leftBold"));
    cell = row.getCell(3);
    cell.setCellStyle(styles.get("item_left_wrap_top"));
    String description = wrapper.getMeeting().getDescription();
    if (description != null && description.length() > 0) {
        description = ExcelPlainTextFormat.convertFormattedHtmlTextToExcelPlaintext(description);
        row.setHeightInPoints(rowHigh * getDescRowNum(description));
    }
    cell.setCellValue(description);
    sheet.addMergedRegion(CellRangeAddress.valueOf("$D$9:$H$9"));

    /* add attachment links */
    int cur_rowNum = 9;
    row = sheet.createRow(cur_rowNum);
    for (int i = 1; i <= 5; i++) {
        row.createCell(i);
    }
    row.setHeightInPoints(rowHigh);
    cell = row.getCell(2);
    cell.setCellValue(rb.getString("attachments"));
    cell.setCellStyle(styles.get("item_leftBold"));
    List<SignupAttachment> attachs = wrapper.getEventMainAttachments();
    if (attachs != null && !attachs.isEmpty()) {
        for (int i = 0; i < attachs.size(); i++) {
            SignupAttachment attach = attachs.get(i);
            if (i > 0) {// start with second attachment
                cur_rowNum++;
                row = sheet.createRow(cur_rowNum);// create next
                // attachment row
                row.setHeightInPoints(rowHigh);
                for (int j = 1; j <= 5; j++) {
                    row.createCell(j);
                }
            }

            cell = row.getCell(3);
            cell.setCellStyle(styles.get("hyperLink"));
            cell.setCellValue(attach.getFilename());
            cell.setHyperlink(setAttachmentURLLinks(attach));
        }
    } else {
        cell = row.getCell(3);
        cell.setCellStyle(styles.get("item_left_wrap"));
        cell.setCellValue(rb.getString("event_no_attachment"));
    }

    /* Case: for announcement event */
    if (ANNOUNCEMENT.equals(wrapper.getMeeting().getMeetingType())) {
        row = sheet.createRow(cur_rowNum + 3);
        row.setHeightInPoints(rowHigh);
        cell = row.createCell(3);
        cell.setCellValue(rb.getString("event_is_open_session",
                "This is an open session meeting. No sign-up is necessary."));
        cell.setCellStyle(styles.get("item_leftBold"));

        return;
    }

    /* Case: for group and individual events */
    // Table titles row
    cur_rowNum = cur_rowNum + 2;
    row = sheet.createRow(cur_rowNum);
    row.setHeightInPoints(rowHigh);
    for (int i = 2; i <= 7; i++) {
        row.createCell(i).setCellStyle(styles.get("tabColNames"));
    }
    cell = row.getCell(2);
    currentTabTitles = isOrganizer(wrapper.getMeeting()) ? tabTitles_Organizor : tabTitles_Participant;
    cell.setCellValue(currentTabTitles[0]);
    sheet.addMergedRegion(CellRangeAddress.valueOf("$C$" + (cur_rowNum + 1) + ":$D$" + (cur_rowNum + 1)));
    cell = row.getCell(4);
    cell.setCellValue(currentTabTitles[1]);
    cell = row.getCell(5);
    cell.setCellValue(currentTabTitles[2]);
    cell = row.getCell(6);
    cell.setCellValue(currentTabTitles[3]);
    cell = row.getCell(7);
    cell.setCellValue(currentTabTitles[4]);

    // Table schedule Info
    int rowNum = cur_rowNum + 1;
    List<SignupTimeslot> tsItems = wrapper.getMeeting().getSignupTimeSlots();
    if (tsItems != null) {
        for (SignupTimeslot tsItem : tsItems) {
            /*strange thing happen for hibernate, it can be null for mySql 4.x*/
            if (tsItem == null) {
                continue;
            }

            row = sheet.createRow(rowNum);
            int rowHighNum = 1;
            rowNum++;
            for (int i = 1; i <= 7; i++) {
                row.createCell(i).setCellStyle(styles.get("tabItem_fields"));
            }
            // timeslot period
            cell = row.getCell(2);
            cell.setCellValue(getTimeSlotPeriod(tsItem, wrapper.getMeeting().isMeetingCrossDays()));
            sheet.addMergedRegion(CellRangeAddress.valueOf("$C$" + rowNum + ":$D$" + rowNum));// "$C$11:$D$11"

            // Max # of participants
            cell = row.getCell(4);
            if (tsItem.isUnlimitedAttendee())
                cell.setCellValue(rb.getString("event_unlimited"));
            else if (isOrganizer(wrapper.getMeeting())) {
                cell.setCellValue(tsItem.getMaxNoOfAttendees());
            } else {
                int availableSpots = getValidAttendees(tsItem.getAttendees()) != null
                        ? tsItem.getMaxNoOfAttendees() - getValidAttendees(tsItem.getAttendees()).size()
                        : tsItem.getMaxNoOfAttendees();
                availableSpots = availableSpots < 1 ? 0 : availableSpots;
                String value = String.valueOf(availableSpots);
                if (tsItem.isLocked())
                    value = rb.getString("event_is_locked");
                else if (tsItem.isCanceled())
                    value = rb.getString("event_is_canceled");

                cell.setCellValue(value);
            }

            List<SignupAttendee> attendees = getValidAttendees(tsItem.getAttendees());

            // attendee names
            cell = row.getCell(5);
            String aNames = rb.getString("event_show_no_attendee_info");
            if (isDisplayNames(wrapper.getMeeting())) {
                if (attendees != null && attendees.size() > rowHighNum) {
                    rowHighNum = attendees.size();
                }
                aNames = getNames(attendees, true);
            }
            if (tsItem.isCanceled() && isOrganizer(wrapper.getMeeting())) {
                aNames = rb.getString("event_is_canceled");
            }
            cell.setCellValue(aNames);
            cell.setCellStyle(styles.get("attendee_layout"));

            // attendee userids
            // without completely reformatting the way the table is constructed, this gives the userids in a separate column
            cell = row.getCell(6);
            String aIds = rb.getString("event_show_no_attendee_info");
            if (isDisplayNames(wrapper.getMeeting())) {
                if (attendees != null && attendees.size() > rowHighNum) {
                    rowHighNum = attendees.size();
                }
                aIds = getIds(attendees);
            }
            if (tsItem.isCanceled() && isOrganizer(wrapper.getMeeting())) {
                aIds = rb.getString("event_is_canceled");
            }
            cell.setCellValue(aIds);
            cell.setCellStyle(styles.get("attendee_layout"));

            // waiters
            cell = row.getCell(7);
            String fieldValue = "";
            if (isOrganizer(wrapper.getMeeting())) {
                List<SignupAttendee> waiters = tsItem.getWaitingList();
                if (waiters != null && waiters.size() > rowHighNum) {
                    rowHighNum = waiters.size();
                }
                fieldValue = getNames(waiters, false);
            } else {
                fieldValue = getYourStatus(tsItem);
            }
            cell.setCellValue(fieldValue);
            cell.setCellStyle(styles.get("attendee_layout"));

            // set row high
            row.setHeightInPoints(rowHigh * rowHighNum);
        }
    }

    // end of table line
    row = sheet.createRow(rowNum);
    for (int i = 2; i <= 7; i++) {
        row.createCell(i).setCellStyle(styles.get("tab_endline"));
    }

    /* process attendee's comments */
    rowNum = rowNum + 2;
    // Comment Title row
    Row commentsRow = sheet.createRow(rowNum);
    commentsRow.setHeightInPoints(25);
    for (int i = 1; i <= 7; i++) {
        commentsRow.createCell(i).setCellStyle(styles.get("commentTitle"));
    }
    Cell commentsCell = commentsRow.getCell(2);
    commentsCell.setCellValue(rb.getString("event_comments_title", "Participant's Comments"));
    sheet.addMergedRegion(CellRangeAddress.valueOf("$C$" + (rowNum + 1) + ":$H$" + (rowNum + 1)));
    // separate line
    rowNum++;
    row = sheet.createRow(rowNum);
    for (int i = 2; i <= 4; i++) {
        row.createCell(i).setCellStyle(styles.get("tab_endline"));
    }

    rowNum++;
    ;
    boolean hasComment = false;
    if (tsItems != null) {
        for (SignupTimeslot ts : tsItems) {
            /*strange thing happen for hibernate, it can be null for mySql 4.x*/
            List<SignupAttendee> attendees = ts != null ? getValidAttendees(ts.getAttendees()) : null;
            if (attendees != null) {
                for (SignupAttendee att : attendees) {
                    if (isOrganizer(wrapper.getMeeting()) || isViewerSelf(att)) {
                        String comment = att.getComments();
                        if (comment != null && comment.trim().length() > 0) {
                            row = sheet.createRow(rowNum++);
                            for (int i = 1; i <= 7; i++) {
                                row.createCell(i);
                            }
                            cell = row.getCell(2);
                            cell.setCellValue(sakaiFacade.getUserDisplayName(att.getAttendeeUserId()) + ":");
                            cell.setCellStyle(styles.get("item_leftBold"));
                            cell = row.getCell(3);
                            cell.setCellStyle(styles.get("item_left_wrap_top"));
                            comment = ExcelPlainTextFormat.convertFormattedHtmlTextToExcelPlaintext(comment);
                            row.setHeightInPoints(rowHigh * getDescRowNum(comment));

                            cell.setCellValue(comment);
                            sheet.addMergedRegion(CellRangeAddress.valueOf("$D$" + rowNum + ":$H$" + rowNum));
                            rowNum++;// one row space between comment
                            hasComment = true;
                        }
                    }
                }
            }
        }

    }

    if (!hasComment) {
        row = sheet.createRow(rowNum);
        row.createCell(2);
        cell = row.getCell(2);
        cell.setCellValue(rb.getString("event_no_comments", "There is no comments written by participants."));
        cell.setCellStyle(styles.get("item_leftBold"));
    }

}

From source file:org.seasar.fisshplate.core.element.Link.java

License:Apache License

void mergeImpl(FPContext context, Cell out) throws FPMergeException {
    String cellValue = getCellValue().toString();
    Matcher mat = pat.matcher(cellValue);
    if (!mat.find()) {
        throw new FPMergeException(FPConsts.MESSAGE_ID_LINK_MERGE_ERROR, new Object[] { cellValue },
                cell.getRow());/*from   www  . j  av a 2s  .  com*/
    }
    String type = mat.group(1);
    String link = mat.group(2);
    String text = mat.group(3);

    LinkElementType linkType = LinkElementType.get(type);
    Hyperlink hyperLink = linkType.createHyperLink();
    hyperLink.setAddress(link);
    out.setHyperlink(hyperLink);
    out.setCellValue(text);

}

From source file:org.spdx.spdxspreadsheet.LicenseSheet.java

License:Apache License

/**
 * Adds a license template to a text cell.  First attempts to create a file and
 * a hyperlink to the file.  If that fails, will attempt to add the text
 * directly to the file./*ww w  .j av a2s .c  o  m*/
 * 
 * @param textCell
 * @param text
 */
public static void setTemplateText(Cell textCell, String text, String licenseId, String textFilePath) {
    String licenseFileName = licenseId + TEXT_EXTENSION;
    File licenseTextFile = new File(textFilePath + File.separator + licenseFileName);
    try {
        if (!licenseTextFile.createNewFile()) {
            logger.warn("Unable to create license text file " + licenseTextFile.getName());
            textCell.setCellValue(text);
            return;
        }
    } catch (IOException e) {
        logger.warn("IO Error creating license text file: " + e.getMessage());
        textCell.setCellValue(text);
        return;
    }
    if (!licenseTextFile.canWrite()) {
        logger.warn("Can not write to text file " + licenseTextFile.getName());
        textCell.setCellValue(text);
        return;
    }
    try {
        Writer out = new OutputStreamWriter(new FileOutputStream(licenseTextFile), ENCODING);
        try {
            out.write(text);
            // add in the hyperlink
            textCell.setCellValue(licenseFileName);
            HSSFHyperlink hyperlink = new HSSFHyperlink(HSSFHyperlink.LINK_FILE);
            hyperlink.setAddress(licenseFileName);
            textCell.setHyperlink(hyperlink);
        } finally {
            out.close();
        }
    } catch (IOException e) {
        logger.warn("Unable to open text file for output: " + e.getMessage());
        textCell.setCellValue(text);
        return;
    }
}

From source file:org.tiefaces.components.websheet.utility.CellUtility.java

License:MIT License

/**
 * set up cell style./* w w  w. j  a  v a2 s.c  o m*/
 * 
 * @param destSheet
 *            dest sheet.
 * @param sourceCell
 *            source cell.
 * @param newCell
 *            new cell.
 */
@SuppressWarnings("deprecation")
private static void copyCellSetStyle(final Sheet destSheet, final Cell sourceCell, final Cell newCell) {
    CellStyle newCellStyle = getCellStyleFromSourceCell(destSheet, sourceCell);
    newCell.setCellStyle(newCellStyle);

    // If there is a cell hyperlink, copy
    if (sourceCell.getHyperlink() != null) {
        newCell.setHyperlink(sourceCell.getHyperlink());
    }

    // Set the cell data type
    newCell.setCellType(sourceCell.getCellTypeEnum());
}

From source file:packtest.HyperlinkExample.java

License:Apache License

public static void main(String[] args) throws Exception {
    Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();

    //cell style for hyperlinks
    //by default hyperlinks are blue and underlined
    CellStyle hlink_style = wb.createCellStyle();
    Font hlink_font = wb.createFont();
    hlink_font.setUnderline(Font.U_SINGLE);
    hlink_font.setColor(IndexedColors.BLUE.getIndex());
    hlink_style.setFont(hlink_font);/*  w  w  w .  j av a2  s.c  o m*/

    Cell cell;
    Sheet sheet = wb.createSheet("Hyperlinks");
    //URL
    cell = sheet.createRow(0).createCell((short) 0);
    cell.setCellValue("URL Link");

    Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL);
    link.setAddress("http://poi.apache.org/");
    cell.setHyperlink(link);
    cell.setCellStyle(hlink_style);

    //link to a file in the current directory
    cell = sheet.createRow(1).createCell((short) 0);
    cell.setCellValue("File Link");
    link = createHelper.createHyperlink(Hyperlink.LINK_FILE);
    link.setAddress("link1.xls");
    cell.setHyperlink(link);
    cell.setCellStyle(hlink_style);

    //e-mail link
    cell = sheet.createRow(2).createCell((short) 0);
    cell.setCellValue("Email Link");
    link = createHelper.createHyperlink(Hyperlink.LINK_EMAIL);
    //note, if subject contains white spaces, make sure they are url-encoded
    link.setAddress("mailto:poi@apache.org?subject=Hyperlinks");
    cell.setHyperlink(link);
    cell.setCellStyle(hlink_style);

    //link to a place in this workbook

    //create a target sheet and cell
    Sheet sheet2 = wb.createSheet("Target Sheet");
    sheet2.createRow(0).createCell((short) 0).setCellValue("Target Cell");

    cell = sheet.createRow(3).createCell((short) 0);
    cell.setCellValue("Worksheet Link");
    Hyperlink link2 = createHelper.createHyperlink(Hyperlink.LINK_DOCUMENT);
    link2.setAddress("'Target Sheet'!A1");
    cell.setHyperlink(link2);
    cell.setCellStyle(hlink_style);

    FileOutputStream out = new FileOutputStream(Utils.getPath("hyperinks.xlsx"));
    wb.write(out);
    out.close();

}

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

License:Open Source License

/**
 * Finish processing for the current (real) cell.
 * @param element//from  www.  ja  v  a  2s . co  m
 * The element that signifies the end of the cell (this may not be an ICellContent object if the 
 * cell is created for a label or text outside of a table). 
 */
protected void endCellContent(HandlerState state, ICellContent birtCell, IContent element, Cell cell,
        Area area) {
    StyleManager sm = state.getSm();
    StyleManagerUtils smu = state.getSmu();

    BirtStyle birtCellStyle = null;
    if (birtCell != null) {
        birtCellStyle = new BirtStyle(birtCell);
        if (element != null) {
            // log.debug( "Overlaying style from ", element );
            birtCellStyle.overlay(element);
        }
    } else if (element != null) {
        birtCellStyle = new BirtStyle(element);
    } else {
        birtCellStyle = new BirtStyle(state.getSm().getCssEngine());
    }
    if (preferredAlignment != null) {
        birtCellStyle.setProperty(StyleConstants.STYLE_TEXT_ALIGN, preferredAlignment);
    }
    if (CSSConstants.CSS_TRANSPARENT_VALUE
            .equals(birtCellStyle.getString(StyleConstants.STYLE_BACKGROUND_COLOR))) {
        if (parent != null) {
            birtCellStyle.setProperty(StyleConstants.STYLE_BACKGROUND_COLOR, parent.getBackgroundColour());
        }
    }
    if (hyperlinkUrl != null) {
        Hyperlink hyperlink = cell.getSheet().getWorkbook().getCreationHelper()
                .createHyperlink(Hyperlink.LINK_URL);
        hyperlink.setAddress(hyperlinkUrl);
        cell.setHyperlink(hyperlink);
    }
    if (hyperlinkBookmark != null) {
        Hyperlink hyperlink = cell.getSheet().getWorkbook().getCreationHelper()
                .createHyperlink(Hyperlink.LINK_DOCUMENT);
        hyperlink.setAddress(prepareName(hyperlinkBookmark));
        cell.setHyperlink(hyperlink);
    }

    if (lastValue != null) {
        if (lastValue instanceof String) {
            String lastString = (String) lastValue;

            smu.correctFontColorIfBackground(birtCellStyle);
            for (RichTextRun run : richTextRuns) {
                run.font = smu.correctFontColorIfBackground(sm.getFontManager(), state.getWb(), birtCellStyle,
                        run.font);
            }

            if (!richTextRuns.isEmpty()) {
                RichTextString rich = smu.createRichTextString(lastString);
                int runStart = richTextRuns.get(0).startIndex;
                Font lastFont = richTextRuns.get(0).font;
                for (int i = 0; i < richTextRuns.size(); ++i) {
                    RichTextRun run = richTextRuns.get(i);
                    log.debug("Run: ", run.startIndex, " font :", run.font);
                    if (!lastFont.equals(run.font)) {
                        log.debug("Applying ", runStart, " - ", run.startIndex);
                        rich.applyFont(runStart, run.startIndex, lastFont);
                        runStart = run.startIndex;
                        lastFont = richTextRuns.get(i).font;
                    }
                }

                log.debug("Finalising with ", runStart, " - ", lastString.length());
                rich.applyFont(runStart, lastString.length(), lastFont);

                setCellContents(cell, rich);
            } else {
                setCellContents(cell, lastString);
            }

            if (lastString.contains("\n")) {
                if (!CSSConstants.CSS_NOWRAP_VALUE.equals(lastElement.getStyle().getWhiteSpace())) {
                    birtCellStyle.setProperty(StyleConstants.STYLE_WHITE_SPACE,
                            new StringValue(StringValue.CSS_STRING, CSSConstants.CSS_PRE_VALUE));
                }
            }
            if (!richTextRuns.isEmpty()) {
                birtCellStyle.setProperty(StyleConstants.STYLE_VERTICAL_ALIGN,
                        new StringValue(StringValue.CSS_STRING, CSSConstants.CSS_TOP_VALUE));
            }
            if (preferredAlignment != null) {
                birtCellStyle.setProperty(StyleConstants.STYLE_TEXT_ALIGN, preferredAlignment);
            }

        } else {
            setCellContents(cell, lastValue);
        }
    }

    int colIndex = cell.getColumnIndex();
    state.getSmu().applyAreaBordersToCell(state.areaBorders, cell, birtCellStyle, state.rowNum, colIndex);

    if ((birtCell != null) && ((birtCell.getColSpan() > 1) || (birtCell.getRowSpan() > 1))) {
        AreaBorders mergedRegionBorders = AreaBorders.createForMergedCells(
                state.rowNum + birtCell.getRowSpan() - 1, colIndex, colIndex + birtCell.getColSpan() - 1,
                state.rowNum, birtCellStyle);
        if (mergedRegionBorders != null) {
            state.insertBorderOverload(mergedRegionBorders);
        }
    }

    String customNumberFormat = EmitterServices.stringOption(state.getRenderOptions(), element,
            ExcelEmitter.CUSTOM_NUMBER_FORMAT, null);
    if (customNumberFormat != null) {
        StyleManagerUtils.setNumberFormat(birtCellStyle, ExcelEmitter.CUSTOM_NUMBER_FORMAT + customNumberFormat,
                null);
    }

    setCellStyle(sm, cell, birtCellStyle, lastValue);

    // Excel auto calculates the row height (if it isn't specified) as long as the cell isn't merged - if it is merged I have to do it
    if (((colSpan > 1) || (state.rowHasSpans(state.rowNum)))
            && ((lastValue instanceof String) || (lastValue instanceof RichTextString))) {
        int spannedRowAlgorithm = EmitterServices.integerOption(state.getRenderOptions(), element,
                ExcelEmitter.SPANNED_ROW_HEIGHT, ExcelEmitter.SPANNED_ROW_HEIGHT_SPREAD);
        Font defaultFont = state.getWb().getFontAt(cell.getCellStyle().getFontIndex());
        double cellWidth = spanWidthMillimetres(state.currentSheet, cell.getColumnIndex(),
                cell.getColumnIndex() + colSpan - 1);
        float cellDesiredHeight = smu.calculateTextHeightPoints(cell.getStringCellValue(), defaultFont,
                cellWidth, richTextRuns);
        if (cellDesiredHeight > state.requiredRowHeightInPoints) {
            int rowSpan = birtCell.getRowSpan();
            if (rowSpan < 2) {
                state.requiredRowHeightInPoints = cellDesiredHeight;
            } else {
                switch (spannedRowAlgorithm) {
                case ExcelEmitter.SPANNED_ROW_HEIGHT_FIRST:
                    state.requiredRowHeightInPoints = cellDesiredHeight;
                    break;
                case ExcelEmitter.SPANNED_ROW_HEIGHT_IGNORED:
                    break;
                default:
                    if (area != null) {
                        area.setHeight(cellDesiredHeight);
                    }
                }
            }
        }
    }

    // Adjust the required row height for any relevant areas based on what's left 
    float rowSpanHeightRequirement = state.calculateRowSpanHeightRequirement(state.rowNum);
    if (rowSpanHeightRequirement > state.requiredRowHeightInPoints) {
        state.requiredRowHeightInPoints = rowSpanHeightRequirement;
    }

    if (EmitterServices.booleanOption(state.getRenderOptions(), element, ExcelEmitter.FREEZE_PANES, false)) {
        if (state.currentSheet.getPaneInformation() == null) {
            state.currentSheet.createFreezePane(state.colNum, state.rowNum);
        }
    }

    lastValue = null;
    lastElement = null;
    richTextRuns.clear();
}