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:gov.nih.nci.evs.app.neopl.CSVtoExcel.java

License:Open Source License

public void runXSSF(String inputfile) {
    int size = checkSpecialCharacters(inputfile);

    int n = inputfile.lastIndexOf(".");
    //String outputfile = inputfile.substring(0, n) + ".xlsx";
    String outputfile = getOutputFile(inputfile, ".xlsx");

    try {/*w  w  w  .  j  av  a  2s. co  m*/
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFCreationHelper helper = null;

        XSSFCellStyle cellStyle = wb.createCellStyle();
        XSSFFont font = wb.createFont();
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        cellStyle.setFont(font);

        XSSFCellStyle linkCellStyle = wb.createCellStyle();
        XSSFFont linkfont = wb.createFont();

        //XSSFColor color = new XSSFColor(Color.LIGHT_BLUE);
        XSSFColor color = new XSSFColor(Color.BLUE);
        linkfont.setColor(color);

        //linkfont.setColor(XSSFColor.LIGHT_BLUE.index);
        linkCellStyle.setFont(linkfont);
        CSVReader reader = new CSVReader(new FileReader(inputfile));//CSV file
        String[] line;
        int r = 0;
        Cell cell = null;

        XSSFHyperlink url_link = null;
        XSSFSheet sheet = null;

        int page_num = 1;
        Row row = null;
        int lcv = 0;
        int row_count = 0;

        try {

            while ((line = reader.readNext()) != null) {
                if (lcv % PAGE_SIZE == 0) {
                    r = 0;
                    String sheetLabel = SHEET_LABEL;
                    if (size > PAGE_SIZE) {
                        sheetLabel = sheetLabel + " (Page " + page_num + ")";
                    }
                    //System.out.println("Creating " + sheetLabel);
                    sheet = wb.createSheet(sheetLabel);
                    helper = sheet.getWorkbook().getCreationHelper();
                    url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL);

                    row = sheet.createRow((short) r);
                    for (int i = 0; i < HEADINGS.length; i++) {
                        String heading = HEADINGS[i];
                        cell = row.createCell(i);
                        cell.setCellValue(heading);
                        cell.setCellStyle(cellStyle);
                    }
                    page_num++;

                } else {
                    String s4 = (String) line[4];
                    s4 = s4.trim();
                    r++;
                    row = sheet.createRow((short) r);
                    row_count++;
                    cell = row.createCell(0);
                    String ncit_code = line[0];
                    cell.setCellValue(ncit_code);
                    if (NCIT_LINK) {
                        url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL);
                        url_link.setAddress(getNCItHyperlink(ncit_code));
                        cell.setHyperlink(url_link);
                        cell.setCellStyle(linkCellStyle);
                    }

                    cell = row.createCell(1);
                    String name = line[1];
                    cell.setCellValue(line[1]);

                    cell = row.createCell(2);
                    cell.setCellValue(line[2]);
                    if (NCIM_LINK) {
                        String s2 = line[2];
                        s2 = s2.trim();
                        if (s2.length() > 0) {
                            url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL);
                            url_link.setAddress(getNCImHyperlink(s2));
                            cell.setHyperlink(url_link);
                            cell.setCellStyle(linkCellStyle);
                        }
                    }

                    cell = row.createCell(3);
                    String ncim_name = line[3];
                    cell.setCellValue(line[3]);

                    cell = row.createCell(4);
                    cell.setCellValue(line[4]);

                    cell = row.createCell(5);
                    String atom_name = (String) line[5];
                    cell.setCellValue(line[5]);

                    cell = row.createCell(6);
                    cell.setCellValue(line[6]);

                    if (SOURCE_LINK) {
                        if (s4.length() > 0) {
                            String s6 = (String) line[6];
                            if (localNameMap.containsKey(s4)) {
                                url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL);
                                s4 = (String) localNameMap.get(s4);
                                url_link.setAddress(getSourceHyperlink(s4, s6));
                                cell.setHyperlink(url_link);
                                cell.setCellStyle(linkCellStyle);
                            }
                        }
                    }
                    cell = row.createCell(7);
                    cell.setCellValue(line[7]);
                }
                lcv++;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // Write the output to a file
        FileOutputStream fileOut = new FileOutputStream(outputfile);
        wb.write(fileOut);
        fileOut.close();
        System.out.println("Output file " + outputfile + " generated.");
        System.out.println("row_count: " + row_count);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:gov.nih.nci.evs.app.neopl.CSVtoExcel.java

License:Open Source License

public void runHSSF(Vector data_vec, String outputfile) {
    if (codeColumn == null) {
        setDefault();//from w  w  w.j  a  v  a 2 s  . co  m
    }

    //int size = 0;//checkSpecialCharacters(inputfile);
    int size = data_vec.size();
    String[] line = null;
    try {
        HSSFWorkbook wb = new HSSFWorkbook();

        HSSFCellStyle cellStyle = wb.createCellStyle();
        //cellStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
        //cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        HSSFFont font = wb.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //font.setColor(HSSFColor.WHITE.index);
        cellStyle.setFont(font);

        HSSFCellStyle linkCellStyle = wb.createCellStyle();
        //cellStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
        //cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        HSSFFont linkfont = wb.createFont();
        linkfont.setColor(HSSFColor.LIGHT_BLUE.index);
        linkCellStyle.setFont(linkfont);

        //CreationHelper helper = wb.getCreationHelper();
        //CSVReader reader = new CSVReader(new FileReader(inputfile));//CSV file

        int r = 0;
        Cell cell = null;

        //"C7419","Acanthoma","C0846967","Acanthoma","MDR","Acanthoma","10059394","LT"
        // skip heading
        HSSFHyperlink url_link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
        HSSFSheet sheet = null;
        int page_num = 1;
        Row row = null;
        //line = reader.readNext();
        int lcv = 0;
        int row_count = 0;
        Vector w = new Vector();
        String nextLine = null;
        Vector values = null;
        for (int k = 0; k < data_vec.size(); k++) {
            nextLine = (String) data_vec.elementAt(k);
            int k1 = k + 1;
            line = toArray(nextLine);
            //if (lcv % PAGE_SIZE == 0) {
            if (lcv == 0) {
                r = 0;
                String sheetLabel = SHEET_LABEL;
                if (size > PAGE_SIZE) {
                    sheetLabel = sheetLabel;// + " (Page " + page_num + ")";
                }
                sheet = wb.createSheet(sheetLabel);

                for (int j = 0; j < HEADINGS.length; j++) {
                    sheet.autoSizeColumn(j);
                }

                row = sheet.createRow((short) r);
                for (int i = 0; i < HEADINGS.length; i++) {
                    String heading = HEADINGS[i];
                    cell = row.createCell(i);
                    cell.setCellValue(heading);
                    cell.setCellStyle(cellStyle);
                }
                sheet.createFreezePane(0, 1); // this will freeze the header row
                page_num++;
            }

            String s4 = line[4];
            if (s4.compareTo("NCI") == 0) {
                w.add("NCI Line number: " + r);
            } else { //if (s4.compareTo("NCI") != 0) {
                r++;
                row = sheet.createRow((short) r);
                row_count++;
                for (int i = 0; i < HEADINGS.length; i++) {
                    cell = row.createCell(i);
                    int codeCol = codeColumn[i];
                    cell.setCellValue(line[i]);
                    if (NCIT_LINK && codeCol == LINK_NCIT) {
                        url_link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
                        String code = line[i];
                        url_link.setAddress(getNCItHyperlink(code));
                        cell.setHyperlink(url_link);
                        cell.setCellStyle(linkCellStyle);
                    } else if (NCIM_LINK && codeCol == LINK_NCIM) {
                        url_link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
                        String code = line[i];
                        url_link.setAddress(getNCImHyperlink(code));
                        cell.setHyperlink(url_link);
                        cell.setCellStyle(linkCellStyle);
                    } else if (SOURCE_LINK && codeCol == LINK_OTHER) {
                        url_link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
                        String code = line[i];
                        String source = line[SOURCE_INDEX];
                        if (localNameMap.containsKey(source)) {
                            url_link.setAddress(getSourceHyperlink(source, code));
                            cell.setHyperlink(url_link);
                            cell.setCellStyle(linkCellStyle);
                        }
                    }
                }

            }
            lcv++;
        }

        // Write the output to a file
        FileOutputStream fileOut = new FileOutputStream(outputfile);
        wb.write(fileOut);
        fileOut.close();
        System.out.println("Output file " + outputfile + " generated.");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:invoiceapplication.CopyRowOriginal.java

public static void copyRow(Sheet worksheet, int sourceRowNum, int destRowNum) {
    // Get the source / new row
    Row newRow = worksheet.getRow(destRowNum);
    Row sourceRow = worksheet.getRow(sourceRowNum);

    // If the row exists in destination, push down all rows by 1 else create a new row
    if (newRow != null) {
        worksheet.shiftRows(newRow.getRowNum(), worksheet.getLastRowNum(), 1, true, true);
    } else {/*from  www  .j a va2s . c o  m*/
        newRow = worksheet.createRow(destRowNum);
    }
    copyAnyMergedRegions(worksheet, sourceRow, newRow);
    // Loops through source column 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 = newRow.createCell(i);

        // if the old cell is null jump to next cell
        if (oldCell == null) {
            newCell = null;
            continue;
        }

        // Use old cell style
        newCell.setCellStyle(oldCell.getCellStyle());

        // If there is a cell comment, copy
        if (newCell.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_FORMULA:
            newCell.setCellValue(oldCell.getCellFormula());
            break;
        case Cell.CELL_TYPE_NUMERIC:
            newCell.setCellValue(oldCell.getNumericCellValue());
            break;
        case Cell.CELL_TYPE_STRING:
            newCell.setCellValue(oldCell.getStringCellValue());
            break;
        }
    }
}

From source file:jp.ryoyamamoto.poiutils.Cells.java

License:Apache License

private static void copyHyperlink(Cell source, Cell target) {
    if (source.getHyperlink() == null) {
        removeHyperlink(target);// ww w . j a v a  2 s.  c om
    } else {
        target.setHyperlink(source.getHyperlink());
    }
}

From source file:opn.greenwebs.HyperlinkExample.java

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);//from w  ww  . ja v a2 s.  co  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("hyperinks.xlsx");
    wb.write(out);
    out.close();

}

From source file:org.apache.tika.eval.reports.XLSXHREFFormatter.java

License:Apache License

@Override
public void applyStyleAndValue(int dbColNum, ResultSet resultSet, Cell cell) throws SQLException {
    if (links < MAX_HYPERLINKS) {
        Hyperlink hyperlink = workbook.getCreationHelper().createHyperlink(linkType);
        String path = resultSet.getString(dbColNum);
        String address = urlBase + path;
        hyperlink.setAddress(address);/*from   w  w w.j  ava  2s .c  o  m*/
        cell.setHyperlink(hyperlink);
        cell.setCellStyle(style);
        String fName = Paths.get(path).getFileName().toString();
        cell.setCellValue(fName);
        links++;
    } else {
        //silently stop adding hyperlinks
    }
}

From source file:org.bbreak.excella.core.util.PoiUtil.java

License:Open Source License

/**
 * ???//from ww w . j a v  a  2  s  .  c o  m
 * 
 * @param cell 
 * @param type 
 * @param address ?
 * @see org.apache.poi.common.usermodel.Hyperlink
 */
public static void setHyperlink(Cell cell, HyperlinkType hyperlinkType, String address) {

    Workbook wb = cell.getRow().getSheet().getWorkbook();

    CreationHelper createHelper = wb.getCreationHelper();

    Hyperlink link = createHelper.createHyperlink(hyperlinkType);
    if (link instanceof HSSFHyperlink) {
        ((HSSFHyperlink) link).setTextMark(address);
    } else if (link instanceof XSSFHyperlink) {
        ((XSSFHyperlink) link).setAddress(address);
    }

    cell.setHyperlink(link);
}

From source file:org.cerberus.service.export.ExportServiceFactory.java

License:Open Source License

private int createRow(String test, HashMap<String, List<TestCaseExecution>> executionsPerTestCase, Sheet sheet,
        int currentIndex, List<String> mapCountries) {

    int lastRow = currentIndex + executionsPerTestCase.size();

    int current = currentIndex;

    TreeMap<String, List<TestCaseExecution>> sortedKeys = new TreeMap<String, List<TestCaseExecution>>(
            executionsPerTestCase);//  www  .j  a va  2s  .c om
    CellStyle wrapStyle = sheet.getColumnStyle(0); //Create new style
    wrapStyle.setWrapText(true); //Set wordwrap

    for (String testCaseKey : sortedKeys.keySet()) {
        List<String> browserEnvironment = new LinkedList<String>();
        String application;
        String description;
        Row r = sheet.createRow(current);
        List<TestCaseExecution> executionList = executionsPerTestCase.get(testCaseKey);
        Cell testCell = r.createCell(0);
        testCell.setCellValue(test);
        testCell.setCellStyle(wrapStyle);
        r.createCell(1).setCellValue(testCaseKey);

        //gets the first object to retrieve the application - at least exists one test case execution
        if (executionList.isEmpty()) {
            application = "N/D";
            description = "N/D";
        } else {
            application = executionList.get(0).getApplication();
            description = executionList.get(0).getTestCaseObj().getBehaviorOrValueExpected();
        }
        //Sets the application and description
        r.createCell(2).setCellValue(application);
        r.createCell(3).setCellValue(description);

        int rowStartedTestCaseInfo = current;

        for (TestCaseExecution exec : executionList) {
            if (browserEnvironment.isEmpty()) {
                browserEnvironment.add(exec.getEnvironment() + "_" + exec.getBrowser());
                r.createCell(4).setCellValue(exec.getEnvironment());
                r.createCell(5).setCellValue(exec.getBrowser());
            } else {
                int index = browserEnvironment.indexOf(exec.getEnvironment() + "_" + exec.getBrowser());

                //Does not exist any information about browser and environment
                if (browserEnvironment.indexOf(exec.getEnvironment() + "_" + exec.getBrowser()) == -1) {
                    //need to add another row with the same characteristics
                    r = sheet.createRow(++current);
                    r.createCell(0).setCellValue(test);
                    r.createCell(1).setCellValue(testCaseKey);
                    r.createCell(2).setCellValue(application);
                    r.createCell(3).setCellValue(description);
                    r.createCell(4).setCellValue(exec.getEnvironment());
                    r.createCell(5).setCellValue(exec.getBrowser());

                    browserEnvironment.add(exec.getEnvironment() + "_" + exec.getBrowser());
                } else {
                    //there is information about the browser and environment
                    Row rowExisting = sheet.getRow(rowStartedTestCaseInfo + index);
                    r = rowExisting;
                }

            }

            //TODO:FN tirar daqui estes valores
            int indexOfCountry = mapCountries.indexOf(exec.getCountry()) + 6;
            Cell executionResult = r.createCell(indexOfCountry);
            executionResult.setCellValue(exec.getControlStatus());
            //Create hyperling
            CreationHelper createHelper = sheet.getWorkbook().getCreationHelper();
            CellStyle hlinkstyle = sheet.getWorkbook().createCellStyle();
            Font hlinkfont = sheet.getWorkbook().createFont();
            hlinkfont.setUnderline(XSSFFont.U_SINGLE);
            hlinkfont.setColor(HSSFColor.BLUE.index);
            hlinkstyle.setFont(hlinkfont);

            Hyperlink link = (Hyperlink) createHelper.createHyperlink(Hyperlink.LINK_URL);
            link.setAddress("http://www.tutorialspoint.com/");
            executionResult.setHyperlink((Hyperlink) link);
            executionResult.setCellStyle(hlinkstyle);

        }
        current++;

    }

    /*r.createCell(1).setCellValue("");
     r.createCell(2).setCellValue("");
     r.createCell(3).setCellValue("");
     r.createCell(4).setCellValue("");
     r.createCell(5).setCellValue("");
     */
    //        for(TestCaseWithExecution exec : execution){
    //            
    //            //r.createCell(2).setCellValue(exec.getDescription());
    //            //r.createCell(3).setCellValue(exec.getApplication());
    //            //r.createCell(4).setCellValue(exec.getEnvironment());
    //            //r.createCell(5).setCellValue(exec.getBrowser());
    //            int indexOfCountry = mapCountries.indexOf(exec.getCountry()) + 6;
    //            r.createCell(indexOfCountry).setCellValue(exec.getControlStatus());
    //            //current++;
    //        }
    //puts the test name in the first column
    /*r = sheet.getRow(currentIndex);
     r.getCell(0).setCellValue(test);
     */
    /*CellRangeAddress range = new CellRangeAddress(currentIndex, lastRow, 0, 0);
     sheet.addMergedRegion(range);*/
    return lastRow;
}

From source file:org.deployom.core.AuditService.java

License:Open Source License

public HSSFWorkbook saveAudit() {

    // Create book
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFCreationHelper creationHelper = workbook.getCreationHelper();

    // Default Style
    HSSFCellStyle style = workbook.createCellStyle();
    style.setWrapText(true);/*from  w  w  w  . java2 s .  co  m*/
    HSSFFont font = workbook.createFont();
    font.setFontName("Courier New");
    style.setFont(font);
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    style.setBorderTop(HSSFCellStyle.BORDER_THIN);
    style.setBorderRight(HSSFCellStyle.BORDER_THIN);
    style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

    // Header Style
    HSSFCellStyle styleHeader = workbook.createCellStyle();
    styleHeader.cloneStyleFrom(style);
    styleHeader.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    font = workbook.createFont();
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    font.setColor(HSSFColor.WHITE.index);
    styleHeader.setFillForegroundColor(IndexedColors.BLACK.getIndex());
    styleHeader.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    styleHeader.setFont(font);

    // Error Style
    HSSFCellStyle styleError = workbook.createCellStyle();
    styleError.cloneStyleFrom(style);
    styleError.setFillForegroundColor(IndexedColors.CORAL.getIndex());
    styleError.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    styleError.setWrapText(true);

    // Link Style
    HSSFCellStyle styleLink = workbook.createCellStyle();
    styleLink.cloneStyleFrom(style);
    font = workbook.createFont();
    font.setUnderline(HSSFFont.U_SINGLE);
    font.setColor(IndexedColors.BLUE.getIndex());
    styleLink.setFont(font);

    // Create Summary
    HSSFSheet summarySheet = workbook.createSheet("Summary");
    int summaryRownum = 0;
    int summaryCellnum = 0;

    //Create a new row in current sheet
    Row summaryRow = summarySheet.createRow(summaryRownum++);

    // 0
    Cell summaryCell = summaryRow.createCell(summaryCellnum++);
    summaryCell.setCellValue("Job");
    summaryCell.setCellStyle(styleHeader);

    // 1
    summaryCell = summaryRow.createCell(summaryCellnum++);
    summaryCell.setCellValue("Finished");
    summaryCell.setCellStyle(styleHeader);

    // 2
    summaryCell = summaryRow.createCell(summaryCellnum++);
    summaryCell.setCellValue("Errors");
    summaryCell.setCellStyle(styleHeader);

    for (Job job : releaseService.getJobs()) {

        // Open Job
        JobService jobService = new JobService(siteService.getSiteName(), job.getJobName());

        // Create Sheet
        HSSFSheet sheet = workbook.createSheet(job.getJobName());

        int rownum = 0;
        int cellnum = 0;
        int errors = 0;

        //Create a new row in current sheet
        Row row = sheet.createRow(rownum++);

        // 0
        Cell cell = row.createCell(cellnum++);
        cell.setCellValue("Host");
        cell.setCellStyle(styleHeader);

        // 1
        cell = row.createCell(cellnum++);
        cell.setCellValue("Service");
        cell.setCellStyle(styleHeader);

        // 2
        cell = row.createCell(cellnum++);
        cell.setCellValue("Command");
        cell.setCellStyle(styleHeader);

        // 3
        cell = row.createCell(cellnum++);
        cell.setCellValue("Executable");
        cell.setCellStyle(styleHeader);

        // 4
        cell = row.createCell(cellnum++);
        cell.setCellValue("Error");
        cell.setCellStyle(styleHeader);

        // 5
        cell = row.createCell(cellnum++);
        cell.setCellValue("Output");
        cell.setCellStyle(styleHeader);

        // Check all hosts
        for (Host host : jobService.getHosts()) {

            // Check all services
            for (Service service : host.getServices()) {

                // Get a Commands
                for (Command command : service.getCommands()) {

                    //Create a new row in current sheet
                    row = sheet.createRow(rownum++);
                    cellnum = 0;

                    // 0
                    cell = row.createCell(cellnum++);
                    cell.setCellValue(host.getHostName());
                    cell.setCellStyle(style);

                    // 1
                    cell = row.createCell(cellnum++);
                    cell.setCellValue(service.getServiceName());
                    cell.setCellStyle(style);

                    // 2
                    cell = row.createCell(cellnum++);
                    cell.setCellValue(command.getTitle());
                    cell.setCellStyle(style);

                    // 3
                    cell = row.createCell(cellnum++);
                    cell.setCellValue(command.getExec());
                    cell.setCellStyle(style);

                    // 4
                    cell = row.createCell(cellnum++);
                    cell.setCellValue("N");
                    cell.setCellStyle(style);

                    // 5
                    cell = row.createCell(cellnum++);
                    if (command.getOut().length() > 1024) {
                        cell.setCellValue(command.getOut().substring(0, 1024) + "...");
                    } else {
                        cell.setCellValue(command.getOut());
                    }
                    cell.setCellStyle(style);

                    // Error
                    if (command.isError() == true) {
                        row.getCell(0).setCellStyle(styleError);
                        row.getCell(1).setCellStyle(styleError);
                        row.getCell(2).setCellStyle(styleError);
                        row.getCell(3).setCellStyle(styleError);
                        row.getCell(4).setCellStyle(styleError);
                        row.getCell(5).setCellStyle(styleError);
                        row.getCell(4).setCellValue("Y");
                        errors++;
                    }
                }
            }
        }

        // Set Size
        sheet.setColumnWidth(0, 6000);
        sheet.setColumnWidth(1, 4000);
        sheet.setColumnWidth(2, 8000);
        sheet.setColumnWidth(3, 14000);
        sheet.setColumnWidth(4, 3000);
        sheet.setColumnWidth(5, 20000);

        // Summary
        summaryRow = summarySheet.createRow(summaryRownum++);
        summaryCellnum = 0;

        // 0
        summaryCell = summaryRow.createCell(summaryCellnum++);
        summaryCell.setCellValue(job.getJobName());
        summaryCell.setCellStyle(style);

        // Set Link
        HSSFHyperlink link = creationHelper.createHyperlink(Hyperlink.LINK_DOCUMENT);
        link.setAddress("" + job.getJobName() + "!A1");
        summaryCell.setHyperlink(link);
        summaryCell.setCellStyle(styleLink);

        // 1
        summaryCell = summaryRow.createCell(summaryCellnum++);
        summaryCell.setCellValue(jobService.getJob().getFinished());
        summaryCell.setCellStyle(style);

        // 2
        summaryCell = summaryRow.createCell(summaryCellnum++);
        summaryCell.setCellValue(errors);
        summaryCell.setCellStyle(style);

        // If errors found
        if (errors > 0) {
            summaryRow.getCell(0).setCellStyle(styleError);
            summaryRow.getCell(1).setCellStyle(styleError);
            summaryRow.getCell(2).setCellStyle(styleError);
        }
    }

    // Set Summary Size
    summarySheet.setColumnWidth(0, 6000);
    summarySheet.setColumnWidth(1, 10000);
    summarySheet.setColumnWidth(2, 4000);

    // Save
    try {
        FileOutputStream out = new FileOutputStream(new File(getFileName()));
        workbook.write(out);
        out.close();
        logger.log(Level.INFO, "{0} generated successfully..", getFileName());

        return workbook;
    } catch (FileNotFoundException ex) {
        logger.log(Level.WARNING, "Audit: {0}", ex);
    } catch (IOException ex) {
        logger.log(Level.WARNING, "Audit: {0}", ex);
    }

    return null;
}

From source file:org.hellojavaer.poi.excel.utils.ExcelUtils.java

License:Apache License

@SuppressWarnings("unused")
private static void writeCell(Cell cell, Object val, boolean userTemplate,
        ExcelWriteFieldMappingAttribute attribute, Object bean) {
    if (attribute != null && attribute.getLinkField() != null) {
        String addressFieldName = attribute.getLinkField();
        String address = null;//from w  ww .j  av  a 2 s. c om
        if (bean != null) {
            address = (String) getFieldValue(bean, addressFieldName, true);
        }
        Workbook wb = cell.getRow().getSheet().getWorkbook();

        Hyperlink link = wb.getCreationHelper().createHyperlink(attribute.getLinkType());
        link.setAddress(address);
        cell.setHyperlink(link);
        // Its style can't inherit from cell.
        CellStyle style = wb.createCellStyle();
        Font hlinkFont = wb.createFont();
        hlinkFont.setUnderline(Font.U_SINGLE);
        hlinkFont.setColor(IndexedColors.BLUE.getIndex());
        style.setFont(hlinkFont);
        if (cell.getCellStyle() != null) {
            style.setFillBackgroundColor(cell.getCellStyle().getFillBackgroundColor());
        }
        cell.setCellStyle(style);
    }
    if (val == null) {
        cell.setCellValue((String) null);
        return;
    }
    Class<?> clazz = val.getClass();
    if (val instanceof Byte) {// Double
        Byte temp = (Byte) val;
        cell.setCellValue((double) temp.byteValue());
    } else if (val instanceof Short) {
        Short temp = (Short) val;
        cell.setCellValue((double) temp.shortValue());
    } else if (val instanceof Integer) {
        Integer temp = (Integer) val;
        cell.setCellValue((double) temp.intValue());
    } else if (val instanceof Long) {
        Long temp = (Long) val;
        cell.setCellValue((double) temp.longValue());
    } else if (val instanceof Float) {
        Float temp = (Float) val;
        cell.setCellValue((double) temp.floatValue());
    } else if (val instanceof Double) {
        Double temp = (Double) val;
        cell.setCellValue((double) temp.doubleValue());
    } else if (val instanceof Date) {// Date
        Date dateVal = (Date) val;
        long time = dateVal.getTime();
        // read is based on 1899/12/31 but DateUtil.getExcelDate is base on
        // 1900/01/01
        if (time >= TIME_1899_12_31_00_00_00_000 && time < TIME_1900_01_01_00_00_00_000) {
            Date incOneDay = new Date(time + 24 * 60 * 60 * 1000);
            double d = DateUtil.getExcelDate(incOneDay);
            cell.setCellValue(d - 1);
        } else {
            cell.setCellValue(dateVal);
        }

        if (!userTemplate) {
            Workbook wb = cell.getRow().getSheet().getWorkbook();
            CellStyle cellStyle = cell.getCellStyle();
            if (cellStyle == null) {
                cellStyle = wb.createCellStyle();
            }
            DataFormat dataFormat = wb.getCreationHelper().createDataFormat();
            // @see #BuiltinFormats
            // 0xe, "m/d/yy"
            // 0x14 "h:mm"
            // 0x16 "m/d/yy h:mm"
            // {@linke https://en.wikipedia.org/wiki/Year_10,000_problem}
            /** [1899/12/31 00:00:00:000~1900/01/01 00:00:000) */
            if (time >= TIME_1899_12_31_00_00_00_000 && time < TIME_1900_01_02_00_00_00_000) {
                cellStyle.setDataFormat(dataFormat.getFormat("h:mm"));
                // cellStyle.setDataFormat(dataFormat.getFormat("m/d/yy h:mm"));
            } else {
                // if ( time % (24 * 60 * 60 * 1000) == 0) {//for time
                // zone,we can't use this way.
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(dateVal);
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                int minute = calendar.get(Calendar.MINUTE);
                int second = calendar.get(Calendar.SECOND);
                int millisecond = calendar.get(Calendar.MILLISECOND);
                if (millisecond == 0 && second == 0 && minute == 0 && hour == 0) {
                    cellStyle.setDataFormat(dataFormat.getFormat("m/d/yy"));
                } else {
                    cellStyle.setDataFormat(dataFormat.getFormat("m/d/yy h:mm"));
                }
            }
            cell.setCellStyle(cellStyle);
        }
    } else if (val instanceof Boolean) {// Boolean
        cell.setCellValue(((Boolean) val).booleanValue());
    } else {// String
        cell.setCellValue((String) val.toString());
    }
}