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:TaskFetcher.java

static HashMap<String, String> fetchAllTasks(String username, String excel_path) {
    HashMap<String, String> alltasks = new HashMap<String, String>();
    FileInputStream file = null;//from  ww  w. ja v  a 2  s  .  co m
    try {
        file = new FileInputStream(new File(excel_path));
    } catch (FileNotFoundException ex) {
        Logger.getLogger(TaskFetcher.class.getName()).log(Level.SEVERE, null, ex);
    }

    //Create Workbook instance holding reference to .xlsx file
    XSSFWorkbook workbook = null;
    try {
        workbook = new XSSFWorkbook(file);
    } catch (IOException ex) {
        Logger.getLogger(TaskFetcher.class.getName()).log(Level.SEVERE, null, ex);
    }

    //Get first sheet from the workbook
    XSSFSheet sheet = workbook.getSheetAt(1);
    Iterator<Row> rowIterator = sheet.iterator();
    if (rowIterator.hasNext())
        rowIterator.next(); //skipping the first row of heading
    while (rowIterator.hasNext()) //loop over all entries in the excel sheet
    {
        Row row = rowIterator.next();
        Cell cell = row.getCell(0);
        if (username.equalsIgnoreCase(cell.getStringCellValue())) {
            String task;
            String status;
            String timestamp;
            String comments;
            task = row.getCell(1).getStringCellValue();
            status = row.getCell(2).getStringCellValue();
            timestamp = row.getCell(3).getStringCellValue();
            comments = row.getCell(4).getStringCellValue();
            alltasks.put(timestamp, task + ":" + status + ":" + comments);
        }
    }
    try {
        workbook.close();
    } catch (IOException ex) {
        Logger.getLogger(TaskFetcher.class.getName()).log(Level.SEVERE, null, ex);
    }
    return alltasks;
}

From source file:action.FacultyAction.java

public String callAddFacultyExcel() {
    System.out.println("we are in Faculty Action excel");
    try {//from w  w  w  . ja v  a  2 s .  c o  m
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(myExcelSheet));

        // Get first sheet from the workbook
        XSSFSheet sheet = wb.getSheetAt(0);

        Row row;
        Cell cell;

        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();
        int i = 0;
        row = rowIterator.next();
        while (rowIterator.hasNext()) {
            row = rowIterator.next();

            // For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext()) {
                cell = cellIterator.next();

                switch (cell.getCellType()) {

                case Cell.CELL_TYPE_STRING: {
                    if (i == 0) {
                        fact.setFactId(cell.getStringCellValue());
                    }
                    if (i == 1) {
                        fact.setFacultyName(cell.getStringCellValue());
                    }
                    if (i == 2) {
                        fact.setFacultyEmail(cell.getStringCellValue());
                    }
                    if (i == 3) {
                        fact.setFacultyAddress(cell.getStringCellValue());
                    }
                    if (i == 4) {
                        fact.setFacultyDept(cell.getStringCellValue());
                    }
                }

                    break;
                }
                i++;
            }
            i = 0;
            System.out.println("Object from excel : " + fact);
            callSaveFaculty();
            System.out.println("Our Obeject");

        }
        System.out.println("");
    } catch (Exception ex) {
        ex.printStackTrace();

    }
    System.out.println("We end");
    return SUCCESS;

}

From source file:action.ResultAction.java

public String callReadExecl() {
    System.out.println("we are here");
    String flag = "success";
    try {//w  w w  . j  a v a 2  s . c om
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(myExcelSheet));

        // Get first sheet from the workbook
        XSSFSheet sheet = wb.getSheetAt(0);

        Row row;
        Cell cell;

        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();
        int i = 0;
        row = rowIterator.next();
        while (rowIterator.hasNext()) {
            row = rowIterator.next();
            System.out.println("iterator Strated");
            // For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();
            int pra[] = new int[4];
            int sub[] = new int[5];
            int j = 0, k = 0, total = 0;
            while (cellIterator.hasNext()) {
                cell = cellIterator.next();

                switch (cell.getCellType()) {

                case Cell.CELL_TYPE_NUMERIC:
                    int a = (int) cell.getNumericCellValue();
                    total = total + a;
                    if (j < 5) {
                        sub[j] = a;
                        j++;
                    } else if (k < 4) {
                        pra[k] = a;
                        k++;
                    }
                    if (i == 2) {
                        stdR.setSemester(a);
                    } else if (i == 3) {
                        stdR.setSub1(a);
                    } else if (i == 4) {
                        stdR.setSub2(a);
                    } else if (i == 5) {
                        stdR.setSub3(a);
                    } else if (i == 6) {
                        stdR.setSub4(a);
                    } else if (i == 7) {
                        stdR.setSub5(a);
                    } else if (i == 8) {
                        stdR.setPra1(a);
                    } else if (i == 9) {
                        stdR.setPra2(a);
                    } else if (i == 10) {
                        stdR.setPra3(a);
                    } else if (i == 11) {
                        stdR.setPra4(a);
                    } else if (i == 12) {
                        stdR.setTotal(a);
                    } else if (i == 13) {
                        stdR.setPercentage((long) cell.getNumericCellValue());
                    }
                    break;

                case Cell.CELL_TYPE_STRING: {
                    if (i == 0) {
                        stdR.setStdRoll(cell.getStringCellValue());
                    } else if (i == 1) {
                        stdR.setBranch(cell.getStringCellValue());
                    }
                }

                    break;
                }
                i++;
            }
            i = 0;
            stdR.setTotal(total);
            System.out.println("Total");
            System.out.println("Student marks : " + stdR);
            subId.setSemid(stdR.getSemester());
            subId.setBranch(stdR.getBranch());
            subject = subDao.getAllSubject(subId);
            stdEx.setStdRollEx(stdR.getStdRoll());
            getStudentExSubject(stdEx);
            if (stdR.getPra1() < 13) {
                list.add(subject.getPra1() + "_");
            }
            if (stdR.getPra2() < 13) {
                list.add(subject.getPra2() + "_");
            }
            if (stdR.getPra3() < 13) {
                list.add(subject.getPra3() + "_");
            }
            if (stdR.getPra4() < 13) {
                list.add(subject.getPra4() + "_");
            }
            if (stdR.getSub1() < 25) {
                list.add(subject.getSub1() + "_");
            }
            if (stdR.getSub2() < 25) {
                list.add(subject.getSub2() + "_");
            }
            if (stdR.getSub3() < 25) {
                list.add(subject.getSub3() + "_");
            }
            if (stdR.getSub4() < 25) {
                list.add(subject.getSub4() + "_");
            }
            if (stdR.getSub5() < 25) {
                list.add(subject.getSub5() + "_");
            }
            String subj = "";
            for (int ii = 0; ii < list.size(); ii++) {
                subj += list.get(ii);
            }

            System.out.println("Subject Ka object : " + subject);
            System.err.println("Student Object : " + stdDetails);
            System.err.println("Student Marks Object : " + stdR);
            System.err.println("Student Ex : " + stdEx);
            stdEx.setStudentExDetailscol(subj);
            stdDetails.setStdRollnumber(stdR.getStdRoll());
            stdDetails = stdDao.getSingleSudentData(stdDetails);
            stdDetails.setStdMarks(stdR);
            stdDetails.setStudentexdetails(stdEx);
            stdR.setStudentDetails(stdDetails);
            stdEx.setStudentDetails(stdDetails);
            //flag = stdDao.updateStudent(stdDetails);
            System.out.println("Subject Ka object : " + subject);
            System.err.println("Student Object : " + stdDetails);
            System.err.println("Student Marks Object : " + stdR);
            System.err.println("Student Ex : " + stdEx);
            callsaveMarks();
            System.out.println("iteration ended");

        }
        System.out.println("");
    } catch (Exception ex) {
        ex.printStackTrace();

    }
    System.out.println("We end");
    return flag;
}

From source file:action.StudentAction.java

public String callGetStudentExcel() {
    System.out.println("we are here");
    try {//from w  w w . ja  va  2s.c  o  m
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(myExcelSheet));

        // Get first sheet from the workbook
        XSSFSheet sheet = wb.getSheetAt(0);

        Row row;
        Cell cell;

        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();
        int i = 0;
        row = rowIterator.next();
        while (rowIterator.hasNext()) {
            row = rowIterator.next();

            // For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();

            while (cellIterator.hasNext()) {
                cell = cellIterator.next();

                switch (cell.getCellType()) {

                case Cell.CELL_TYPE_NUMERIC:
                    if (i == 5) {
                        stdDetails.setStdSemester((int) cell.getNumericCellValue());
                    } else if (i == 7) {
                        stdDetails.setStdContact((long) cell.getNumericCellValue());
                    }
                    break;

                case Cell.CELL_TYPE_STRING: {
                    if (i == 0) {
                        stdDetails.setStdRollnumber(cell.getStringCellValue());
                    } else if (i == 1) {
                        stdDetails.setStdName(cell.getStringCellValue());
                    } else if (i == 2) {
                        stdDetails.setStdEmail(cell.getStringCellValue());
                    } else if (i == 3) {
                        stdDetails.setStdBatch(cell.getStringCellValue());
                    } else if (i == 4) {
                        stdDetails.setStdBranch(cell.getStringCellValue());
                    } else if (i == 6) {
                        stdDetails.setStdAddress(cell.getStringCellValue());
                    }
                }

                    break;
                }
                i++;
            }
            i = 0;
            callSaveStudent();
            System.out.println("Our Obeject");
            System.out.println(stdDetails);
        }
        System.out.println("");
    } catch (Exception ex) {
        ex.printStackTrace();

    }
    System.out.println("We end");
    return SUCCESS;
}

From source file:Actionclasses.ReadExcel.java

public ReadExcel(String filePath) {
    filelocation = filePath;/*from  w w  w .ja  va 2 s.c o m*/
    try {
        FileInputStream file = new FileInputStream(new File(filelocation));
        //new workbook is created
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        //new sheet is created
        XSSFSheet sheet = workbook.getSheetAt(0);
        /*rowIterator - Returns an iterator of the physical rows
           iterator - Alias for rowIterator() to allow foreach loops
        So basically they return the same values, but the second was added 
        to support Java's for-each loop. In other words, instead of getting the iterator
        and running while loop, you could directly run for-each loop, which makes code 
        shorter and more readable
                     */
        //Creating random table
        Insert();
        //loop for iterate in each row
        for (Row row : sheet) {
            //List list=new ArrayList();
            //loop for iterate in each cell in a particular row
            for (Cell cell : row) {
                cell.setCellType(CELL_TYPE_STRING);
                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.println("boolean===>>>\"+cell.getBooleanCellValue() + \"\\t");
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    break;
                case Cell.CELL_TYPE_STRING:
                    //list.add(cell.getStringCellValue());
                    System.out.println(cell.getStringCellValue());
                    break;
                }
            }
            String Name = row.getCell(0).getStringCellValue();
            String Emailid = row.getCell(1).getStringCellValue();
            System.out.println(Name + " " + Emailid);
            Insertindb(Name, Emailid);
        }
        //file.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ReadExcel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ReadExcel.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:adams.data.io.input.ExcelSpreadSheetReader.java

License:Open Source License

/**
 * Reads the spreadsheet content from the specified file.
 *
 * @param in      the input stream to read from
 * @return      the spreadsheets or null in case of an error
 *///ww  w.ja v a2  s. co m
@Override
protected List<SpreadSheet> doReadRange(InputStream in) {
    List<SpreadSheet> result;
    int[] indices;
    Workbook workbook;
    Sheet sheet;
    SpreadSheet spsheet;
    Row exRow;
    Cell exCell;
    adams.data.spreadsheet.Row spRow;
    int i;
    int n;
    int cellType;
    DateFormat dformat;
    boolean numeric;
    int dataRowStart;
    int firstRow;
    int lastRow;
    List<String> header;

    result = new ArrayList<>();

    workbook = null;
    dformat = DateUtils.getTimestampFormatter();
    try {
        workbook = WorkbookFactory.create(in);
        m_SheetRange.setMax(workbook.getNumberOfSheets());
        indices = m_SheetRange.getIntIndices();
        firstRow = m_FirstRow - 1;
        dataRowStart = getNoHeader() ? firstRow : firstRow + 1;
        for (int index : indices) {
            if (m_Stopped)
                break;

            spsheet = m_SpreadSheetType.newInstance();
            spsheet.setDataRowClass(m_DataRowType.getClass());
            result.add(spsheet);

            if (isLoggingEnabled())
                getLogger().info("sheet: " + (index + 1));

            sheet = workbook.getSheetAt(index);
            if (sheet.getLastRowNum() == 0) {
                getLogger().severe("No rows in sheet #" + index);
                return null;
            }
            spsheet.setName(sheet.getSheetName());

            // header
            if (isLoggingEnabled())
                getLogger().info("header row");
            exRow = sheet.getRow(firstRow);
            if (exRow == null) {
                getLogger().warning("No data in sheet #" + (index + 1) + "?");
            } else if (exRow != null) {
                spRow = spsheet.getHeaderRow();
                m_TextColumns.setMax(exRow.getLastCellNum());
                if (getNoHeader()) {
                    header = SpreadSheetUtils.createHeader(exRow.getLastCellNum(), m_CustomColumnHeaders);
                    for (i = 0; i < header.size(); i++)
                        spRow.addCell("" + (i + 1)).setContent(header.get(i));
                } else {
                    if (!m_CustomColumnHeaders.trim().isEmpty()) {
                        header = SpreadSheetUtils.createHeader(exRow.getLastCellNum(), m_CustomColumnHeaders);
                        for (i = 0; i < header.size(); i++)
                            spRow.addCell("" + (i + 1)).setContent(header.get(i));
                    } else {
                        for (i = 0; i < exRow.getLastCellNum(); i++) {
                            if (m_Stopped)
                                break;
                            exCell = exRow.getCell(i);
                            if (exCell == null) {
                                spRow.addCell("" + (i + 1)).setMissing();
                                continue;
                            }
                            numeric = !m_TextColumns.isInRange(i);
                            switch (exCell.getCellType()) {
                            case Cell.CELL_TYPE_BLANK:
                            case Cell.CELL_TYPE_ERROR:
                                spRow.addCell("" + (i + 1)).setContent("column-" + (i + 1));
                                break;
                            case Cell.CELL_TYPE_NUMERIC:
                                if (HSSFDateUtil.isCellDateFormatted(exCell))
                                    spRow.addCell("" + (i + 1)).setContent(new DateTime(
                                            HSSFDateUtil.getJavaDate(exCell.getNumericCellValue())));
                                else if (numeric)
                                    spRow.addCell("" + (i + 1)).setContent(exCell.getNumericCellValue());
                                else
                                    spRow.addCell("" + (i + 1)).setContentAsString(numericToString(exCell));
                                break;
                            default:
                                spRow.addCell("" + (i + 1)).setContentAsString(exCell.getStringCellValue());
                            }
                        }
                    }
                }
            }

            // data
            if (spsheet.getColumnCount() > 0) {
                if (m_NumRows < 1)
                    lastRow = sheet.getLastRowNum();
                else
                    lastRow = Math.min(firstRow + m_NumRows - 1, sheet.getLastRowNum());
                for (i = dataRowStart; i <= lastRow; i++) {
                    if (m_Stopped)
                        break;
                    if (isLoggingEnabled())
                        getLogger().info("data row: " + (i + 1));
                    spRow = spsheet.addRow("" + spsheet.getRowCount());
                    exRow = sheet.getRow(i);
                    if (exRow == null)
                        continue;
                    for (n = 0; n < exRow.getLastCellNum(); n++) {
                        // too few columns in header?
                        if ((n >= spsheet.getHeaderRow().getCellCount()) && m_AutoExtendHeader)
                            spsheet.insertColumn(spsheet.getColumnCount(), "");

                        m_TextColumns.setMax(spsheet.getHeaderRow().getCellCount());
                        exCell = exRow.getCell(n);
                        if (exCell == null) {
                            spRow.addCell(n).setMissing();
                            continue;
                        }
                        cellType = exCell.getCellType();
                        if (cellType == Cell.CELL_TYPE_FORMULA)
                            cellType = exCell.getCachedFormulaResultType();
                        numeric = !m_TextColumns.isInRange(n);
                        switch (cellType) {
                        case Cell.CELL_TYPE_BLANK:
                        case Cell.CELL_TYPE_ERROR:
                            if (m_MissingValue.isEmpty())
                                spRow.addCell(n).setMissing();
                            else
                                spRow.addCell(n).setContent("");
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            if (HSSFDateUtil.isCellDateFormatted(exCell))
                                spRow.addCell(n).setContent(
                                        dformat.format(HSSFDateUtil.getJavaDate(exCell.getNumericCellValue())));
                            else if (numeric)
                                spRow.addCell(n).setContent(exCell.getNumericCellValue());
                            else
                                spRow.addCell(n).setContentAsString(numericToString(exCell));
                            break;
                        default:
                            if (m_MissingValue.isMatch(exCell.getStringCellValue()))
                                spRow.addCell(n).setMissing();
                            else
                                spRow.addCell(n).setContentAsString(exCell.getStringCellValue());
                        }
                    }
                }
            }
        }
    } catch (Exception ioe) {
        getLogger().log(Level.SEVERE, "Failed to read range '" + m_SheetRange + "':", ioe);
        result = null;
        m_LastError = "Failed to read range '" + m_SheetRange + "' from stream!\n"
                + Utils.throwableToString(ioe);
    }

    return result;
}

From source file:addCE.ExcelReader.java

public void read() {

    try {//  w ww  .ja v  a2s. co m

        FileInputStream excelFile = new FileInputStream(new File(excelFileName));
        Workbook workbook = new XSSFWorkbook(excelFile);
        Sheet datatypeSheet = workbook.getSheetAt(0);
        Iterator<Row> iterator = datatypeSheet.iterator();

        iterator.next();
        iterator.next();
        iterator.next();

        while (iterator.hasNext()) {

            Row currentRow = iterator.next();
            ArrayList<String> data = new ArrayList<String>();
            Iterator<Cell> cellIterator = currentRow.iterator();

            while (cellIterator.hasNext()) {

                Cell currentCell = cellIterator.next();
                //getCellTypeEnum shown as deprecated for version 3.15
                //getCellTypeEnum will be renamed to getCellType starting from version 4.0
                if (currentCell == null || currentCell.getCellTypeEnum() == CellType.BLANK) {
                    data.add("None");
                } else if (currentCell.getCellTypeEnum() == CellType.STRING) {
                    data.add(currentCell.getStringCellValue());
                    //System.out.print(currentCell.getStringCellValue() + "--");
                } else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
                    data.add(Double.toString(currentCell.getNumericCellValue()));
                    //System.out.print(currentCell.getNumericCellValue() + "--");
                }

            }
            this.attendees.add(data);

        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ADP_Streamline.MatrixReader.java

public String check() throws Exception {

    List<String> ClientRoles = new ArrayList<>();
    List<String> PartnerRoles = new ArrayList<>();
    List<String> ADPRoles = new ArrayList<>();
    List<String> Rights = new ArrayList<>();

    String rightscolumn = "";
    String rights = "";
    String roles = "";
    String cellwithx;//  ww  w .  j  av a 2s .co m

    int righstrow = 0;
    int columncount;
    int rowcount;
    int roleslenght;
    int rightslenght = 0;

    Boolean client = false;
    Boolean partner = false;
    Boolean adp;
    Boolean rightstart = false;

    Iterator<Row> rowIterator;
    Iterator<Cell> cellIterator;

    Row row;
    Cell cell;

    OracleJDBC oracle = new OracleJDBC();

    try {

        FileInputStream file = new FileInputStream(
                new File("C:\\Users\\frodri1\\Documents\\SPM 1.2_RoleMatrix_Demo.xlsx"));

        //Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(file);

        //Get first/desired sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);

        //Iterate through each rows one by one
        rowIterator = sheet.iterator();

        rowcount = 2;
        columncount = 0;

        while (rowIterator.hasNext()) {

            row = rowIterator.next();
            //if(adp) {break;}
            adp = false;

            //For each row, iterate through all the columns
            cellIterator = row.cellIterator();

            while (cellIterator.hasNext()) {

                cell = cellIterator.next();

                if (cell.getStringCellValue().contentEquals("Right")) {
                    rightscolumn = CellReference.convertNumToColString(cell.getColumnIndex());
                    righstrow = cell.getRowIndex();
                    rightstart = true;
                }

                if (cell.getStringCellValue().contentEquals("Client")) {
                    client = true;
                }

                if (cell.getStringCellValue().contentEquals("Partner")) {
                    partner = true;
                    client = false;
                }

                if (cell.getStringCellValue().contentEquals("ADP")) {
                    partner = false;
                    client = false;
                    adp = true;
                }

                if (client) {
                    ClientRoles.add(
                            CellIteration(sheet, CellReference.convertNumToColString(cell.getColumnIndex()),
                                    righstrow, columncount, 0).trim());
                }

                if (partner) {
                    PartnerRoles.add(
                            CellIteration(sheet, CellReference.convertNumToColString(cell.getColumnIndex()),
                                    righstrow, columncount, 0).trim());
                }

                if (adp) {
                    ADPRoles.add(
                            CellIteration(sheet, CellReference.convertNumToColString(cell.getColumnIndex()),
                                    righstrow, columncount, 0).trim());
                }
            }

            if (rightstart) {

                rights = CellIteration(sheet, rightscolumn, righstrow, columncount, rowcount);

                if (!"".equals(rights)) {

                    Rights.add(rights.trim());
                    rightslenght++;
                    rowcount++;
                } else
                    break;
            }
        }

        roleslenght = ClientRoles.size() + PartnerRoles.size() + ADPRoles.size();

        for (int i = 0; i < rightslenght; i++) {

            for (int l = 0; l < roleslenght; l++) {

                cellwithx = CellIteration(sheet, rightscolumn, righstrow, l + 1, i + 2);
                if ("x".equals(cellwithx)) {

                    if (l < ClientRoles.size()) {

                        rights = Rights.get(i);
                        roles = ClientRoles.get(l);

                        oracle.check(rights, roles);
                    }

                    if (l >= ClientRoles.size() && l < (ClientRoles.size() + PartnerRoles.size())) {

                        rights = Rights.get(i);
                        roles = PartnerRoles.get(l - ClientRoles.size());

                    }

                    if (l >= ClientRoles.size() + PartnerRoles.size()) {

                        rights = Rights.get(i);
                        roles = ADPRoles.get(l - (ClientRoles.size() + PartnerRoles.size()));

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

    return "";
}

From source file:Algorithm.Method1.java

public String[] MethodTest(String Path) {
    StringBuffer keyword1 = new StringBuffer();
    try {//from w  w  w . j ava  2s. com
        Hashtable hash = new Hashtable();

        FileInputStream file = new FileInputStream(new File(Path));
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet sheet1 = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet1.iterator();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            //Row rowNew =sheetNew.createRow(rowNumNew++);
            //For each row, iterate through all the columns
            Iterator<org.apache.poi.ss.usermodel.Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                org.apache.poi.ss.usermodel.Cell cell = cellIterator.next();
                // Cell cellNew =rowNew.createCell(cellNumNew++);
                //Check the cell type and format accordingly
                switch (cell.getCellType()) {
                case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC:
                    break;
                case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING:
                    String result = cell.getStringCellValue();
                    if (hash.containsKey(result)) {
                        int f = Integer.parseInt(hash.get(result).toString());
                        f++;
                        hash.put(result, f);
                    } else {
                        hash.put(result, 1);
                    }

                }
            }

            //System.out.println("");
        }

        XSSFWorkbook workbookNew = new XSSFWorkbook();
        XSSFSheet sheetNew = workbookNew.createSheet("test");
        int rowNum = 0;

        Set s = hash.keySet();
        String key = new String();
        int t = 0;
        for (Iterator<String> i = s.iterator(); i.hasNext();) {
            key = i.next();
            Row rowNew = sheetNew.createRow(rowNum);
            org.apache.poi.ss.usermodel.Cell cellNew = rowNew.createCell(0);
            cellNew.setCellValue(key);
            keyword1.append(key + " ");
            org.apache.poi.ss.usermodel.Cell cellNew2 = rowNew.createCell(1);
            cellNew2.setCellValue(hash.get(key).toString());
            rowNum++;
            //sheet2.addCell(new Label(0,t , key));
            //System.out.println(hash.get(key));
            //sheet2.addCell(new Label(1,t , hash.get(key).toString()));
            t++;
        }

        FileOutputStream fileOut = new FileOutputStream(new File(Path.replace("???.xlsx", "method1.xlsx")));//new file
        workbookNew.write(fileOut);
        fileOut.close();

        file.close();

        // Workbook book = Workbook.getWorkbook(new File("n.xls"));

        //WritableWorkbook book2 = Workbook.createWorkbook(new File("method1.xls"));
        //
        // WritableSheet sheet2 = book2.createSheet("num1", 0);

        // 
        //Sheet sheet = book.getSheet(0);         
        //int rownum = sheet.getRows();// 
        /**
        Cell cell;
        for(int i = 0;i<rownum;i++){
           cell = sheet.getCell(0,i);
           String result = cell.getContents();
           if(hash.containsKey(result)){
          int f = Integer.parseInt(hash.get(result).toString());
          f++;
          hash.put(result, f);
           }else{
          hash.put(result, 1);
           }
        }
        */
        //??
        /*
        Set s=hash.keySet();
        String key = new String();
        int t = 0;
        for(Iterator<String> i=s.iterator();i.hasNext();){
           key = i.next();
           sheet2.addCell(new Label(0,t , key));
        //System.out.println(hash.get(key));
        sheet2.addCell(new Label(1,t , hash.get(key).toString()));
        t++;
        }
                
        book2.write();
        book2.close();
        */
        // book.close();
        System.out.print("method1");
    } catch (Exception e) {
        System.out.println(e);
    }
    return keyword1.toString().split(" ");
}

From source file:Algorithm.Method1.java

public String[] method1Out(String filepath) throws Exception {

    File fileout = new File("pp.txt");
    PrintWriter out1 = new PrintWriter(fileout);

    String[] out = null;//from  w  w  w .ja  v a  2 s.c  om
    ArrayList outList = new ArrayList<String>();
    String result;
    Hashtable hash = new Hashtable();
    FileInputStream file = new FileInputStream(new File(filepath));
    XSSFWorkbook workbook = new XSSFWorkbook(file);
    XSSFSheet sheet1 = workbook.getSheetAt(0);
    Iterator<Row> rowIterator = sheet1.iterator();
    //???excel?????
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();

        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            result = cell.getStringCellValue().trim();
            if (hash.containsKey(result)) {
                int f = Integer.parseInt(hash.get(result).toString());
                f++;
                hash.put(result, f);

            } else {
                hash.put(result, 1);

            }
        } //end while
    } //end while

    //???tf-idf
    Hashtable hash_2 = new Hashtable();
    File filein = new File("tfidf.txt");
    Scanner input = new Scanner(filein);
    String s;
    double d;

    while (input.hasNext()) {

        s = input.next().trim();
        d = input.nextDouble();

        hash_2.put(s, d);
    }

    //??
    Set ss = hash.keySet();
    String key = new String();
    //tf-idf
    for (Iterator<String> i = ss.iterator(); i.hasNext();) {
        key = i.next().trim();

        if (hash_2.containsKey(key)) {
            int tf = Integer.parseInt(hash.get(key).toString());
            double idf = Double.parseDouble(hash_2.get(key).toString());
            hash.put(key, tf * idf);
            //out1.println(key+" "+tf*idf);
        } else {
            hash.put(key, 0.1);
            //out1.println(key+" "+0.1);
        }

    }

    key = null;

    //tf-idf?
    Set ss2 = hash.keySet();

    String tmp = "";

    int size = hash.size();
    for (int j = 0; j < size; j++) {
        ss2 = hash.keySet();
        double max = 0;
        for (Iterator<String> i = ss2.iterator(); i.hasNext();) {
            key = i.next().trim();
            double xxoo = Double.parseDouble(hash.get(key).toString());
            if (xxoo > max) {
                //??
                max = xxoo;
                tmp = key;

            }

        }

        hash.remove(tmp);

        ss = hash.keySet();

        if (!outList.contains(tmp))
            outList.add(tmp);

    }

    //arraylist?
    out = (String[]) outList.toArray(new String[1]);

    //out1.close();
    /*
    for(int i=0;i<out.length;i++)
    {
    System.out.print(out[i]);
    }
        */
    return out;
}