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

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

Introduction

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

Prototype

String getStringCellValue();

Source Link

Document

Get the value of the cell as a string

For numeric cells we throw an exception.

Usage

From source file:com.amitycoin.enterprisetool.diagramInputServlet.java

@Override
@SuppressWarnings({ "null", "ValueOfIncrementOrDecrementUsed", "UnusedAssignment" })
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String filePath;/*from w  ww.  j  a v a2 s  .co m*/
    String docids;
    String userid;
    String a[][];
    a = new String[200][200];
    // database connection settings
    String dbURL = "jdbc:mysql://localhost:3306/enterprisedb";
    String dbUser = "root";
    String dbPass = "sandy";

    @SuppressWarnings("UnusedAssignment")
    Connection conn = null; // connection to the database
    userid = (String) request.getAttribute("uidM");
    String fname = (String) request.getAttribute("fnameM");
    int docid = (Integer) request.getAttribute("docidM");

    docids = "" + docid;
    String pathToWeb;
    pathToWeb = getServletContext().getRealPath(File.separator);
    System.out.println("pathtoweb:\t" + pathToWeb);
    filePath = pathToWeb + "readFiles\\";
    filePath = filePath + docids + userid + fname; //+.xls
    File myFile = new File(filePath);

    //boolean newExcel;
    //boolean oldExcel;
    String ext = FilenameUtils.getExtension(filePath);
    System.out.println("Extension: " + ext);

    FileInputStream fis = new FileInputStream(myFile);
    Workbook wb = null;
    if ("xls".equals(ext)) {
        // Finds the workbook instance for the file
        wb = new HSSFWorkbook(fis);

    } else if ("xlsx".equals(ext)) {
        wb = new XSSFWorkbook(fis);

    }

    @SuppressWarnings("null")
    Sheet mySheet;
    mySheet = wb.getSheetAt(0);

    // Get iterator to all the rows in current sheet
    Iterator<Row> rowIterator = mySheet.iterator();

    @SuppressWarnings("UnusedAssignment")
    int rowct = 0, colct = 0, colit = 0, ci = 0, ri = 0;

    // Traversing over each row of XLSX file
    while (rowIterator.hasNext()) {
        ri++;
        System.out.println("\nRi:\t" + ri);
        //Iterate over Rows
        Row row = rowIterator.next();

        if (1 == rowct) {
            colct = colit;
        }
        // For each row, iterate through each columns
        Iterator<Cell> cellIterator = row.cellIterator();
        ci = 0;
        while (cellIterator.hasNext()) {

            ci++;

            System.out.println("\nCi:\t" + ci);
            //Iterate over Columns
            Cell cell = cellIterator.next();

            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                System.out.print(cell.getStringCellValue() + "\t");
                a[ri][ci] = cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                System.out.print(cell.getNumericCellValue() + "\t");
                double temp = cell.getNumericCellValue();
                String dblValue = "" + temp;
                a[ri][ci] = dblValue;
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                System.out.print(cell.getBooleanCellValue() + "\t");
                String tmp = "" + cell.getBooleanCellValue();
                a[ri][ci] = tmp;
                break;
            default:

            }
            colit++;

        }
        //rowit++;
        rowct++;
        //increase row count
    }

    System.out.println("Row Count:\t" + rowct);
    System.out.println("Column Count:\t" + colct);
    for (int i = 1; i <= rowct; i++) {
        for (int j = 1; j <= colct; j++) {
            System.out.println("a[" + i + "][" + j + "]=" + a[i][j] + "\n");
        }
    }
    try {
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
        String append = "?, ?";
        String quest = ", ?";

        for (int j = 1; j <= colct; j++) {
            append += quest;
        }

        String crsql;
        String cappend = "`uid`,`doc_id`";
        for (int j = 1; j <= colct; j++) {
            cappend = cappend + ",`" + j + "`";
        }
        crsql = "CREATE TABLE IF NOT EXISTS `data" + userid + docid + "` (\n"
                + "`row_id` INT(11) NOT NULL AUTO_INCREMENT,\n" + "`uid` VARCHAR(50) NOT NULL,\n"
                + "`doc_id` INT(11) NOT NULL";
        System.out.println(crsql);

        for (int j = 1; j <= colct; j++) {
            System.out.println("j:\t" + (j));
            crsql = crsql + ",\n`" + (j) + "` VARCHAR(50)";
        }
        crsql += ",\nPRIMARY KEY (`row_id`)\n)";

        System.out.println(crsql);

        PreparedStatement cstmt = conn.prepareStatement(crsql);
        int c = cstmt.executeUpdate();

        String sql = "INSERT INTO data" + userid + docid + "(" + cappend + ")" + " values (" + append + ")";
        System.out.println("Append=\t" + append);
        PreparedStatement statement = conn.prepareStatement(sql);
        statement.setString(1, userid);
        statement.setInt(2, docid);
        for (int i = 1; i <= rowct; i++) {
            for (int j = 1; j <= (colct); j++) {
                statement.setString(j + 2, a[i][j]);
                System.out.println("j=" + (j) + "\ta[" + i + "][" + (j) + "]=" + a[i][j] + "\n");
            }
            System.out.println("\n");
            System.out.println("\nstatement:\t" + statement);
            int res = statement.executeUpdate();
        }
    } catch (SQLException ex) {
        Logger.getLogger(diagramInputServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    for (int i = 1; i <= rowct; i++) {
        for (int j = 1; j <= colct; j++) {
            System.out.println("a[" + i + "][" + j + "]=" + a[i][j] + "\n");
        }
    }
    System.out.println("Rowct:\t" + rowct + "\nColct:\t" + colct);
    @SuppressWarnings("UseOfObsoleteCollectionType")
    Hashtable<String, Object> style = new Hashtable<String, Object>();
    style.put(mxConstants.STYLE_FILLCOLOR, mxUtils.getHexColorString(Color.WHITE));
    style.put(mxConstants.STYLE_STROKEWIDTH, 1.5);
    style.put(mxConstants.STYLE_STROKECOLOR, mxUtils.getHexColorString(new Color(0, 0, 170)));
    style.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_ELLIPSE);
    style.put(mxConstants.STYLE_PERIMETER, mxConstants.PERIMETER_ELLIPSE);

    graph = new mxGraph();

    mxStylesheet stylesheet = graph.getStylesheet();
    stylesheet.putCellStyle("process", createProcessStyle());
    stylesheet.putCellStyle("object", createObjectStyle());
    stylesheet.putCellStyle("state", createStateStyle());
    stylesheet.putCellStyle("agent", createAgentLinkStyle());
    fr = new JFrame("Enterprise Architecture Diagram");

    fr.setSize(2000, 2000);
    graph.setMinimumGraphSize(new mxRectangle(0, 0, 1000, 1500));
    graph.setMaximumGraphBounds(new mxRectangle(0, 0, 2000, 2000));
    graph.setMinimumGraphSize(new mxRectangle(0, 0, 1000, 1000));

    double rech1 = 200;
    double rech2 = 200;
    double rech3 = 170;
    double rech3e = 180;
    double rech4 = 120;
    Object defaultParent = graph.getDefaultParent();

    graph.setConstrainChildren(true);
    graph.setExtendParents(true);
    graph.setExtendParentsOnAdd(true);
    graph.setDefaultOverlap(0);
    graph.setCellsMovable(true); // Moving cells in the graph. Note that an edge is also a cell.
    graph.setCellsEditable(true);
    graph.setCellsResizable(true); // Inhibit cell re-sizing.

    graph.getModel().beginUpdate();

    Object[] obj = new Object[100];
    int k = 1;
    for (int i = 2; i <= rowct; i++) {
        for (int j = 1; j <= 2; j++) {
            obj[k] = a[i][j];
            k++;
        }

    }

    //print debug info
    for (int l = 1; l <= (rowct * 2) - 2; l++) {
        System.out.println("obj[" + l + "]:\t" + obj[l]);
    }

    List<Object> list = new ArrayList<Object>();
    for (Object val : obj) {
        if (!list.contains(val)) {
            list.add(val);
        }
    }

    list.remove(null);
    list.toArray(new Object[0]);
    System.out.println("list:" + list);

    Object[] array = new Object[list.size()];
    list.toArray(array); // fill the array
    System.out.println("Array:\t" + Arrays.toString(array));

    Object[] gArray = new Object[array.length];
    String[] sArray = new String[array.length];

    for (int i = 0; i < array.length; i++) {
        sArray[i] = array[i].toString();
        if (sArray[i].contains("Database") || sArray[i].contains("Server") || sArray[i].contains("DATABASE")
                || sArray[i].contains("SERVER") || sArray[i].contains("DB")) {
            System.out.println("Object type");
            gArray[i] = graph.insertVertex(defaultParent, null, sArray[i], rech1, rech2, rech3, rech4,
                    "object");

        } else {
            System.out.println("Process type");
            gArray[i] = graph.insertVertex(defaultParent, null, sArray[i], rech1, rech2, rech3e, rech4,
                    "process");
        }
        rech1 += 100;
        rech2 += 100;
    }

    for (int i = 2; i <= rowct; i++) {

        if (a[i][3].equals("Two Way") || a[i][3].equals("TWO WAY") || a[i][3].equals("TwoWay")
                || a[i][3].equals("TWOWAY") || a[i][3].equals("2 Way") || a[i][3].equals("Two way")) {
            System.out.println("Double Edges");
            int l1 = 0, l2 = 0;
            for (int l = 1; l < gArray.length; l++) {
                System.out.println("gArray.toString=\t" + sArray[l]);
                System.out.println("gArray.length=\t" + sArray.length);
                if (sArray[l].equals(a[i][1])) {
                    l1 = l;
                    System.out.println("l2:\t" + l1);
                }
                if (sArray[l].equals(a[i][2])) {
                    l2 = l;
                    System.out.println("l2:\t" + l2);
                }
            }
            graph.insertEdge(defaultParent, null, a[i][4], gArray[l1], gArray[l2], "agent");
            graph.insertEdge(defaultParent, null, a[i][4], gArray[l2], gArray[l1], "agent");

        } else {
            System.out.println("Single Edges");
            int l1 = 0, l2 = 0;
            for (int l = 1; l < gArray.length; l++) {
                System.out.println("gArray.toString=\t" + sArray[l]);
                System.out.println("gArray.length=\t" + sArray.length);
                if (sArray[l].equals(a[i][1])) {
                    l1 = l;
                    System.out.println("l2:\t" + l2);
                }
                if (sArray[l].equals(a[i][2])) {
                    l2 = l;
                    System.out.println("l2:\t" + l2);
                }
            }
            graph.insertEdge(defaultParent, null, a[i][4], gArray[l1], gArray[l2], "agent");
        }
    }

    graph.setEnabled(true);

    graph.setAutoSizeCells(true);

    graph.getModel().endUpdate();

    graphComponent = new mxGraphComponent(graph);
    mxFastOrganicLayout layout = new mxFastOrganicLayout(graph);
    // define layout

    //set all properties
    layout.setMinDistanceLimit(1);
    //layout.setInitialTemp(5);
    //layout.setInitialTemp(10);
    //layout.setForceConstant(10);
    //layout.setDisableEdgeStyle(true);
    //layout graph
    //layout.execute(graph.getDefaultParent());
    // layout using morphing
    String fileWPath;

    graph.getModel().beginUpdate();
    try {
        layout.execute(graph.getDefaultParent());
    } finally {
        mxMorphing morph = new mxMorphing(graphComponent, 20, 1.2, 20);

        morph.addListener(mxEvent.DONE, new mxIEventListener() {

            @Override
            public void invoke(Object arg0, mxEventObject arg1) {
                graph.getModel().endUpdate();
                // fitViewport();
            }

        });

        BufferedImage image;
        image = mxCellRenderer.createBufferedImage(graph, null, 2, Color.WHITE, true, null);
        Document d = mxCellRenderer.createVmlDocument(graph, null, 1, Color.WHITE, null);
        pathToWeb = getServletContext().getRealPath(File.separator);
        System.out.println("pathtoweb:\t" + pathToWeb);
        fileWPath = pathToWeb + "genImg\\" + userid + docid + ".png";
        System.out.println("filewpath:\t" + fileWPath);
        //System.out.println(pathToWeb + userid + docid + ".svg");
        ImageIO.write(image, "PNG", new File(fileWPath));
        XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
                new FileOutputStream(new File(pathToWeb + "genXML\\" + userid + docid + ".xml"))));
        encoder.writeObject(graph);
        encoder.close();
        morph.startAnimation();
    }

    graphComponent.setConnectable(false);
    fr.getRootPane().setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.WHITE));
    // Inhibit edge creation in the graph.
    fr.getContentPane().add(graphComponent);

    //fr.setVisible(true);

    request.setAttribute("docidM", docid);
    request.setAttribute("useridM", userid);
    request.setAttribute("colCountM", colct);
    request.setAttribute("rowCountM", rowct);
    request.setAttribute("fileLinkM", fileWPath);
    request.setAttribute("pathToWebM", pathToWeb);
    System.out.println("Iteration Complete");

    getServletContext().getRequestDispatcher("/success.jsp").forward(request, response);

}

From source file:com.anevis.jfreechartsamplespring.reader.FileReaderServiceImpl.java

@Override
public List<PieChartData> readPieChartDataFromXls(String filepath) {
    InputStream stream;//from   w  w w .  j  a  va2  s.co  m

    try {
        stream = new FileInputStream(filepath);
        List<PieChartData> pieChartDataList = new ArrayList<>();
        HSSFWorkbook workbook = new HSSFWorkbook(stream);

        HSSFSheet sheet = workbook.getSheetAt(0);

        Iterator<Row> rowIterator = sheet.iterator();
        rowIterator.next();

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            PieChartData data = new PieChartData();

            Cell countryCell = row.getCell(0);
            Cell weightCell = row.getCell(1);

            if (countryCell != null && weightCell != null) {
                data.setCountry(countryCell.getStringCellValue());
                data.setWeight(weightCell.getNumericCellValue());

                pieChartDataList.add(data);
            }
        }

        return pieChartDataList;

    } catch (IOException ex) {
        Logger.getLogger(FileReaderServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:com.anritsu.mcrepositorymanager.utils.GenerateRSS.java

public String getRSS() {
    FileInputStream file = null;/* ww w  .  j a v a2  s  . c  o m*/
    String rssFileName = rssTemplateFileName.replaceAll("template", mcVersion);
    try {
        file = new FileInputStream(
                new File(Configuration.getInstance().getRssTemplatePath() + rssTemplateFileName));
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        workbook.setSheetName(workbook.getSheetIndex("MC X.X.X"), "MC " + mcVersion);
        XSSFSheet sheet = workbook.getSheet("MC " + mcVersion);
        CreationHelper createHelper = workbook.getCreationHelper();

        Cell cell = null;

        // Update the sheet title
        cell = sheet.getRow(0).getCell(0);
        cell.setCellValue(cell.getStringCellValue().replaceAll("template", mcVersion));

        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);

        XSSFCellStyle hlinkstyle = workbook.createCellStyle();
        XSSFFont hlinkfont = workbook.createFont();
        hlinkfont.setUnderline(XSSFFont.U_SINGLE);
        hlinkfont.setColor(HSSFColor.BLUE.index);
        hlinkstyle.setFont(hlinkfont);
        hlinkstyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        hlinkstyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        hlinkstyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        hlinkstyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);

        XSSFCellStyle dateCellStyle = workbook.createCellStyle();
        dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd-MMMM-yyyy"));
        dateCellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        dateCellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        dateCellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        dateCellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);

        // Populate the table
        int rowCount = 1;
        for (RecommendedMcPackage rmcp : sortedMcPackages) {
            if (rmcp.getRecommendedVersion() != null && rmcp.isShowInTable()) {
                Row row = sheet.createRow(rowCount + 1);
                rowCount++;

                cell = row.createCell(0);
                cell.setCellValue(rmcp.getTier().replaceAll("Anritsu/MasterClaw/", ""));
                cell.setCellStyle(cellStyle);

                cell = row.createCell(1);
                cell.setCellValue(rmcp.getGroup());
                cell.setCellStyle(cellStyle);

                cell = row.createCell(2);
                cell.setCellValue(rmcp.getPackageName());

                UrlValidator defaultValidator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);

                if (rmcp.getRecommendedVersion().getReleaseNote() != null
                        && defaultValidator.isValid(rmcp.getRecommendedVersion().getReleaseNote())) {
                    XSSFHyperlink releaseNotelink = (XSSFHyperlink) createHelper
                            .createHyperlink(Hyperlink.LINK_URL);
                    releaseNotelink.setAddress(rmcp.getRecommendedVersion().getReleaseNote());
                    //System.out.println("Inside(if) RN: " + rmcp.getRecommendedVersion().getReleaseNote() + " Valid: " + defaultValidator.isValid(rmcp.getRecommendedVersion().getReleaseNote()));

                    cell.setHyperlink(releaseNotelink);
                }
                cell.setCellStyle(hlinkstyle);

                cell = row.createCell(3);
                cell.setCellValue(rmcp.getRecommendedVersion().getPackageVersion());
                cell.setCellStyle(cellStyle);

                cell = row.createCell(4);
                cell.setCellValue(rmcp.getAvailability());
                cell.setCellStyle(cellStyle);

                cell = row.createCell(5);
                String customers = Arrays.asList(rmcp.getRecommendedVersion().getCustomerList().toArray())
                        .toString();
                if (customers.equalsIgnoreCase("[All]")) {
                    customers = "";
                }
                cell.setCellValue(customers);
                cell.setCellStyle(cellStyle);

                cell = row.createCell(6);
                cell.setCellValue(rmcp.getRecommendedVersion().getRisk());
                cell.setCellStyle(cellStyle);

                cell = row.createCell(7);
                cell.setCellValue(rmcp.getPackageName());
                XSSFHyperlink link = (XSSFHyperlink) createHelper.createHyperlink(Hyperlink.LINK_URL);
                link.setAddress(rmcp.getRecommendedVersion().getDownloadLinks().iterator().next());
                cell.setHyperlink((XSSFHyperlink) link);
                cell.setCellStyle(hlinkstyle);

                cell = row.createCell(8);
                cell.setCellValue((rmcp.getRecommendedVersion() != null
                        && rmcp.getRecommendedVersion().isLessRecommended()) ? "#" : "");
                cell.setCellStyle(cellStyle);

                cell = row.createCell(9);
                cell.setCellValue(rmcp.getRecommendedVersion().getNotes());
                cell.setCellStyle(cellStyle);

                StringBuilder newFeatures = new StringBuilder();
                for (MCPackageActivities mcpa : rmcp.getRecommendedVersion().getActivities()) {
                    if (!mcpa.getActivityType().equalsIgnoreCase("epr")) {
                        newFeatures.append(mcpa.getActivityType() + " " + mcpa.getActivityId() + "; ");
                    }
                }
                cell = row.createCell(10);
                cell.setCellValue(newFeatures.toString());
                cell.setCellStyle(cellStyle);

                cell = row.createCell(11);
                cell.setCellValue(rmcp.getRecommendedVersion().getReleaseDate());
                cell.setCellStyle(dateCellStyle);
            }
            sheet.autoSizeColumn(0);
            sheet.autoSizeColumn(1);
            sheet.autoSizeColumn(2);
            sheet.autoSizeColumn(3);
            sheet.autoSizeColumn(4);
            sheet.autoSizeColumn(6);
            sheet.autoSizeColumn(7);
            sheet.autoSizeColumn(8);
            sheet.autoSizeColumn(11);

        }

        FileOutputStream outFile = new FileOutputStream(
                new File(Configuration.getInstance().getRssTemplatePath() + rssFileName));
        workbook.write(outFile);
        outFile.close();
        return Configuration.getInstance().getRssTemplatePath() + rssFileName;

    } catch (FileNotFoundException ex) {
        Logger.getLogger(GenerateRSS.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GenerateRSS.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            file.close();
        } catch (IOException ex) {
            Logger.getLogger(GenerateRSS.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return "";
}

From source file:com.antonov.elparser.impl.domain.ExcelWorker.java

public String getUniversity() throws Exception {

    String result = null;/*from w  w  w .  j a  v  a 2  s  .c o m*/

    try (FileInputStream is = new FileInputStream(filePath)) {

        Workbook wb = WorkbookFactory.create(is);
        Sheet sheet = wb.getSheetAt(0);
        Row row = sheet.getRow(ROW_UNIVERSITY);
        Cell cell = row.getCell(COLUMN_UNIVERSITY);
        result = cell.getStringCellValue().split("-")[1].trim();
    } catch (Throwable ex) {
        String message = "  ?? ?  ";
        logger.error(message, ex);
        throw new Exception(message, ex);
    }
    return result;
}

From source file:com.antonov.elparser.impl.domain.ExcelWorker.java

public List<User> getUsers() throws Exception {
    List<User> result = new ArrayList<>();
    try (FileInputStream is = new FileInputStream(filePath)) {

        Workbook wb = WorkbookFactory.create(is);
        Sheet sheet = wb.getSheetAt(0);/*from   w  w w . j  a v a  2s  . c  o m*/

        int amountRows = sheet.getPhysicalNumberOfRows();

        for (int i = HEADER_HEIGHT; i < amountRows; i++) {
            User user = new User();

            Row row = sheet.getRow(i);
            Cell cell = row.getCell(COLUMN_FIO);
            String fio = cell.getStringCellValue().trim();
            if (fio != null && !fio.isEmpty()) {
                user.setFIO(fio);
                user.setRow(i);
                result.add(user);
            }

        }
    } catch (Throwable ex) {
        String message = "  ??   ";
        logger.error(message, ex);
        throw new Exception(message, ex);
    }
    return result;
}

From source file:com.appdynamics.jrbronet.projectplan.ExcelManager.java

public void AddUpdateAppLicenseData(String appName, HashMap licCount) {
    // Locate where to write, if you find a cell with the same name on the app that this one the update, if not, as you get an empty cell create it
    // For copying cells use copyRow() capable of copying full rows
    // A new app can be copied from the worksheet DataValidationValues rows 50-57

    try {/*from  w ww.j ava 2 s .  c  o m*/

        XSSFSheet worksheet = book.getSheetAt(1); //Accesing the second tab
        XSSFSheet dataValworksheet = book.getSheetAt(2); //Accesing the second tab

        Cell cell = null; // declare a Cell object

        int i = 0;
        boolean found = false;

        if (worksheet.getRow(13) != null) {
            cell = worksheet.getRow(13).getCell(0); // Access the second cell in second row to update the value             
            String thisAppName = cell.getStringCellValue();
            //System.out.println("Cell Contents: "+thisAppName);

            for (i = 0; worksheet.getRow(13 + (i * 8)) != null; i++) {
                cell = worksheet.getRow(13 + (i * 8)).getCell(0); // Access the second cell in second row to update the value             
                thisAppName = cell.getStringCellValue();
                //System.out.println("Cell Contents: "+thisAppName);
                if (thisAppName.equals(appName)) {
                    // Update agent lic usage
                    System.out.println("Updating " + appName);
                    found = true;
                    for (int k = 0; k < 8; k++) {
                        String type = worksheet.getRow(13 + (i * 8) + k).getCell(3).getStringCellValue();
                        Integer lics = (Integer) licCount.get(type);
                        if (lics != null)
                            worksheet.getRow(13 + (i * 8) + k).getCell(4).setCellValue(lics);
                    }
                }
            }
        }

        if (!found) {
            // Create a new entry
            System.out.println("Creating " + appName);
            for (int j = 0; j < 8; j++) {
                copyRow(book, dataValworksheet, 50 + j, worksheet, (13 + i * 8) + j);
                //worksheet.getRow(13+(i*8)+j).getCell(2).setCellValue("=B"+(13+(i*8)));
                worksheet.getRow(13 + (i * 8) + j).getCell(2).setCellFormula("B" + (14 + (i * 8)));
                String type = worksheet.getRow(13 + (i * 8) + j).getCell(3).getStringCellValue();
                //System.out.println("type: "+type);
                Integer lics = (Integer) licCount.get(type);
                //System.out.println("ExcelManager - "+type+": "+lics+" "+licCount.size());
                if (lics != null)
                    worksheet.getRow(13 + (i * 8) + j).getCell(4).setCellValue(lics);
            }
            worksheet.getRow(13 + (i * 8)).getCell(0).setCellValue(appName);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.appspot.backstreetfoodies.server.XLSParser.java

License:Apache License

public XLSParser(InputStream inputStream, int sheetIndex, int numColumnsExpected) throws IOException {
    HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
    HSSFSheet sheet = workbook.getSheetAt(sheetIndex);

    Iterator<Row> rowIterator = sheet.iterator();
    Iterator<Cell> cellIterator;

    numColumns = numColumnsExpected;//w w  w.j a  va 2  s. co  m

    while (rowIterator.hasNext()) {
        int numCellsInRow = 0;
        Row row = rowIterator.next();
        cellIterator = row.cellIterator();
        ArrayList<String> temp = new ArrayList<String>();

        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                if (!String.valueOf(cell.getNumericCellValue()).isEmpty()) {
                    numCellsInRow++;
                    temp.add(String.valueOf(cell.getNumericCellValue()));
                }
                break;
            case Cell.CELL_TYPE_STRING:
                if (!cell.getStringCellValue().isEmpty()) {
                    numCellsInRow++;
                    temp.add(cell.getStringCellValue().trim());
                }
                break;
            default:
                break;
            }
        }

        if (numCellsInRow == numColumnsExpected) {
            xlsData.add(temp);
        }
    }
}

From source file:com.asakusafw.testdata.generator.excel.ExcelTesterRoot.java

License:Apache License

/**
 * Obtains the cell./* w w w.j  av a 2s.co  m*/
 * @param sheet the sheet
 * @param rowIndex row index
 * @param columnIndex column index
 * @return cell string
 */
protected String cell(Sheet sheet, int rowIndex, int columnIndex) {
    Row row = sheet.getRow(rowIndex);
    assertThat(row, not(nullValue()));
    Cell cell = row.getCell(columnIndex);
    if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
        return null;
    }
    assertThat(cell.getCellType(), is(Cell.CELL_TYPE_STRING));
    return cell.getStringCellValue();
}

From source file:com.asakusafw.testdriver.excel.DefaultExcelRuleExtractor.java

License:Apache License

private String getStringCell(Sheet sheet, int rowIndex, int colIndex) {
    assert sheet != null;
    Row row = sheet.getRow(rowIndex);/*w w w  .ja  v  a 2  s .  co  m*/
    if (row == null) {
        return "?"; //$NON-NLS-1$
    }
    Cell cell = row.getCell(colIndex);
    if (cell == null || cell.getCellType() != Cell.CELL_TYPE_STRING) {
        return "?"; //$NON-NLS-1$
    }
    return cell.getStringCellValue();
}

From source file:com.asakusafw.testdriver.excel.DefaultExcelRuleExtractor.java

License:Apache License

@Override
public String extractName(Row row) throws FormatException {
    if (row == null) {
        throw new IllegalArgumentException("row must not be null"); //$NON-NLS-1$
    }//from   ww  w .  ja  va 2  s . c  o  m
    // strict checking for cell type
    Cell cell = row.getCell(RuleSheetFormat.PROPERTY_NAME.getColumnIndex());
    if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
        return null;
    } else if (cell.getCellType() != Cell.CELL_TYPE_STRING) {
        throw new FormatException(MessageFormat.format(
                Messages.getString("DefaultExcelRuleExtractor.errorInvalidNameType"), //$NON-NLS-1$
                RuleSheetFormat.PROPERTY_NAME.getTitle(), cell.getRowIndex() + 1, cell.getColumnIndex() + 1));
    }
    String name = cell.getStringCellValue();
    if (name.isEmpty()) {
        return null;
    }
    return name;
}