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

public List<city> readcityFromExcelFile(String excelFilePath) throws IOException {
    List<city> listcity = new ArrayList<>();
    FileInputStream inputStream = new FileInputStream(new File(excelFilePath));

    Workbook workbook = new XSSFWorkbook(inputStream);
    Sheet firstSheet = workbook.getSheetAt(0);
    Iterator<Row> iterator = firstSheet.iterator();

    while (iterator.hasNext()) {
        Row nextRow = iterator.next();//from w  w w.j av  a  2s.  c  om

        Iterator<Cell> cellIterator = nextRow.cellIterator();
        city acity = new city();

        while (cellIterator.hasNext()) {
            Cell nextCell = cellIterator.next();
            int columnIndex = nextCell.getColumnIndex();

            switch (columnIndex) {
            case 0:
                acity.setCompany(nextCell.getStringCellValue());
                break;
            case 1:
                acity.setFrom(nextCell.getStringCellValue());
                break;
            case 2:

                acity.setTo(nextCell.getStringCellValue());
                break;

            case 3:

                acity.setFare(nextCell.getNumericCellValue());

                break;
            case 4:
                acity.setTime(nextCell.getNumericCellValue());
                break;
            }

        }
        listcity.add(acity);

    }

    workbook.close();
    inputStream.close();

    return listcity;
}

From source file:TestCaseReaderTest.java

private String getCellValueStr(Cell cell) {
    if (cell.CELL_TYPE_STRING == 1) {
        String toret = null;//from  w ww.j  a v a  2  s .com
        try {
            toret = cell.getStringCellValue();
        } catch (NullPointerException npe) {
            return "";
        }

        return toret;
    } else {
        return "";
    }
}

From source file:ExcelConverter.java

public List<ScheduleClass> Converter() throws FileNotFoundException, IOException {
    ArrayList<ScheduleClass> scheduleList = new ArrayList<>();

    FileInputStream fis = new FileInputStream(pathFile);

    XSSFWorkbook wb = new XSSFWorkbook(fis);
    XSSFSheet sheet = wb.getSheetAt(0);//  w  ww. j a va 2  s.  c  om
    Iterator<Row> rowIterator = sheet.iterator();

    CellRangeAddress add;
    int colNoIdx = 0;
    ArrayList<String> dosen = new ArrayList<>();
    ArrayList<Integer> idxDosen = new ArrayList<>();
    ArrayList<Integer> colDosen = new ArrayList<>();
    ArrayList<String> location = new ArrayList<>();
    int idxNumber = 0;
    ArrayList<Integer> locationIdx = new ArrayList<>();
    outerloop: for (int j = 0; j < sheet.getLastRowNum(); j++) {
        row = sheet.getRow(j);
        for (int f = 0; f < row.getLastCellNum(); f++) {
            Cell cell = row.getCell(j);
            if (cell.getStringCellValue().contains("No.")) {
                rowNoIdx = j;
                colNoIdx = cell.getColumnIndex();

                break outerloop;
            }
        }
    }
    outerloop2: for (int i = 0; i < sheet.getLastRowNum(); i++) {
        row = sheet.getRow(i);
        outerloop: for (int j = 0; j < row.getLastCellNum(); j++) {
            Cell cell = row.getCell(j);
            FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
            if (cell.getColumnIndex() == colNoIdx && i > rowNoIdx + 3
                    && evaluator.evaluate(cell).getCellType() != Cell.CELL_TYPE_NUMERIC) {
                i = sheet.getLastRowNum();
                break outerloop2;
            }

            if (cell.getRowIndex() > rowNoIdx + 1 && cell.getColumnIndex() == (colNoIdx + 1)) {
                String delims = "[,. ]";
                String[] sumary = cell.getStringCellValue().split(delims);
                for (int l = 0; l < sumary.length; l++) {
                    if (sumary[l].equalsIgnoreCase("Mrt")) {
                        sumary[l] = "3";
                    }
                }

                lc = LocalDate.of(Integer.parseInt(sumary[5]), Integer.parseInt(sumary[3]),
                        Integer.parseInt(sumary[2]));
            }
            if (cell.getRowIndex() > rowNoIdx + 1 && cell.getColumnIndex() == (colNoIdx + 2)) {
                if (cell.getStringCellValue().equalsIgnoreCase("LIBUR")) {
                    i = i + 1;
                    break outerloop;
                } else {
                    String delimsJam = "[-]";
                    String[] arrJam = cell.getStringCellValue().split(delimsJam);
                    for (int k = 0; k < arrJam.length; k++) {
                        arrJam[k] = arrJam[k].replace('.', ':');
                    }
                    lt = LocalTime.parse(arrJam[0]);
                }

            }
            if (cell.getRowIndex() > rowNoIdx + 1 && cell.getColumnIndex() == (colNoIdx + 5)) {
                subject = cell.getStringCellValue();
            }

            if (cell.getRowIndex() > rowNoIdx && cell.getColumnIndex() >= colNoIdx + 6
                    && cell.getColumnIndex() < row.getLastCellNum()) {
                if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                }
                if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                    if (cell.getStringCellValue().contains(":")) {
                        String[] splt = cell.getStringCellValue().split(":");
                        String[] splt2 = splt[1].split(",");
                        for (int l = 0; l < splt2.length; l++) {
                            dosen.add(splt2[l].trim());
                            location.add("Lab");
                        }
                    } else {
                        CellReference cr = new CellReference(1, cell.getColumnIndex());
                        Row row2 = sheet.getRow(cr.getRow());
                        Cell c = row2.getCell(cr.getCol());
                        if (!cell.getStringCellValue().isEmpty()) {
                            dosen.add(cell.getStringCellValue().trim());
                            location.add(String.valueOf((int) c.getNumericCellValue()).trim());
                        }
                    }

                }
                if (cell.getCellType() == Cell.CELL_TYPE_BLANK && cell.getRowIndex() > 2) {
                    CellReference cr = new CellReference(cell.getRowIndex() - 1, cell.getColumnIndex());
                    Row row2 = sheet.getRow(cr.getRow());
                    Cell c = row2.getCell(cr.getCol());
                    CellReference cr2 = new CellReference(1, cell.getColumnIndex());
                    Row row3 = sheet.getRow(cr2.getRow());
                    Cell c2 = row3.getCell(cr2.getCol());
                    if (c.getStringCellValue().contains(":")) {
                        String[] splt = c.getStringCellValue().split(":");
                        String[] splt2 = splt[1].split(",");
                        for (int l = 0; l < splt2.length; l++) {
                            dosen.add("".trim());
                            location.add("");
                        }
                    } else {
                        if (!c.getStringCellValue().isEmpty()) {
                            dosen.add("");
                            location.add("");
                        }
                    }
                }
            }
        }

        for (int j = 0; j < dosen.size(); j++) {
            scheduleList
                    .add(new ScheduleClass(lc, lt, lt.plusHours(2), subject, dosen.get(j), location.get(j)));
        }
        dosen.clear();
        location.clear();

    }

    return Mergering(scheduleList);
}

From source file:TimeInOut2.java

private boolean statusValidator(Cell status, int currentRow) {
    try {//from  w w  w  .ja  v  a2 s.  c o m
        if (status.getStringCellValue().equals("IN") || status.getStringCellValue().equals("OUT")) {
            return true;
        } else {
            logs.append("Status at row " + currentRow + " is not Valid.\n");
            return false;
        }
    } catch (Exception ex) {
        logs.append("Status at row " + currentRow + " is not Valid.\n");
        return false;
    }
}

From source file:UploadImage.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    if (null == session.getAttribute("idsupp")) {
        response.sendRedirect("public/pages/supplier/login_soft.jsp");
    }//from ww  w .j  a v a2 s.co  m
    PrintWriter out = response.getWriter();
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    System.out.println("request: " + request);
    if (!isMultipart) {
        System.out.println("File Not Uploaded");
    } else {
        System.out.println("File  Uploaded");
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
            Connection cnx = DriverManager.getConnection("jdbc:derby://localhost:1527/pcdb", "pcdbun",
                    "pcdbpw");

            try {

                items = upload.parseRequest(request);
                System.out.println("items: " + items);
            } catch (Exception e) {
                e.printStackTrace();
                //System.out.println(e);
            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    System.out.println("name: " + name);
                    String value = item.getString();
                    System.out.println("value: " + value);
                } else {
                    try {
                        /*
                                    *note to self:
                                    *this isn't my code
                                    *i need to understand how he randomly name the files
                                    **
                                    */
                        String itemName = item.getName();
                        Random generator = new Random();
                        int r = Math.abs(generator.nextInt());

                        String reg = "[.*]";
                        String replacingtext = "";
                        System.out.println("Text before replacing is:-" + itemName);
                        Pattern pattern = Pattern.compile(reg);
                        Matcher matcher = pattern.matcher(itemName);
                        StringBuffer buffer = new StringBuffer();

                        while (matcher.find()) {
                            matcher.appendReplacement(buffer, replacingtext);
                        }
                        int IndexOf = itemName.indexOf(".");
                        String domainName = itemName.substring(IndexOf);
                        System.out.println("domainName: " + domainName);

                        String finalimage = buffer.toString() + "_" + r + domainName;
                        System.out.println("Final Image===" + finalimage);

                        File savedFile = new File(
                                "/home/ayoub/NetBeansProjects/pricomp/web/images/" + finalimage);
                        item.write(savedFile);

                        try ( //print elements from excel file
                                FileInputStream file = new FileInputStream(new File(
                                        "/home/ayoub/NetBeansProjects/pricomp/web/images/" + finalimage))
                        //Get the workbook instance for XLS file
                        ) {
                            XSSFWorkbook workbook;
                            workbook = new XSSFWorkbook(file);

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

                            //Get iterator to all the rows in current sheet
                            Iterator<Row> rowIterator = sheet.iterator();
                            Row firstRow = rowIterator.next();
                            //          int idprod=4;
                            //get the number of lines in table first
                            String sql = "SELECT COUNT(*) AS number FROM PRODUCTS";

                            //out.println();
                            Statement stat = cnx.createStatement();

                            ResultSet rs = stat.executeQuery(sql);
                            rs.next();
                            int idprod = Integer.parseInt(rs.getString("number"));
                            //System.out.println(idprod);

                            while (rowIterator.hasNext()) {
                                idprod++;
                                Row row = rowIterator.next();

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

                                Cell cell = cellIterator.next();
                                String name = cell.getStringCellValue();
                                cell = cellIterator.next();
                                float price = (float) cell.getNumericCellValue();

                                String insertTableSQL = "INSERT INTO products VALUES (?,?,?,?)";
                                //String sql="insert into SUPPLIERS  values("+request.getParameter("name")+","+request.getParameter("adresse")+","+request.getParameter("email")+","+request.getParameter("password")+","+tel+")";
                                PreparedStatement pst = cnx.prepareStatement(insertTableSQL);
                                //int num=Integer.parseInt(request.getParameter("numero"));

                                int idsupp = Integer.parseInt(session.getAttribute("idsupp").toString());
                                //pst.setInt(1,idprod);
                                //pst.setString(1, );
                                pst.setInt(1, idprod);
                                pst.setString(2, name);
                                pst.setFloat(3, price);
                                pst.setInt(4, idsupp);
                                int rset = pst.executeUpdate();

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

                            }
                        }

                        /*
                            Statement stat=cnx.createStatement();
                                 
                        String sqll="insert into suppliers (adressesupp,nomsupp) values('11','hatim')";
                           int rss=stat.executeUpdate(sqll);*/
                        //name=&adresse=&telephone=&password=&email=&description=
                        //String telephone=request.getParameter("telephone");
                        //int tel=Integer.parseInt(telephone);

                        // int rs=stat.executeUpdate("insert into suppliers (nomsupp,adressesup,emailsupp) values ('z','g','g')");
                        // int rs=stat.executeUpdate(sql);

                        response.sendRedirect("public/pages/supplier/homeSupplier.html");

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

    }
}

From source file:ImporteerExcelsheet.java

public void importeerExcelsheet(String filePath) {
    try {//from ww  w  .j a  v  a 2s .  c om
        FileInputStream file = new FileInputStream(new File(filePath));

        if (filePath.toLowerCase().indexOf(xlsx.toLowerCase()) != -1) {
            XSSFWorkbook wbXlsx = new XSSFWorkbook(file);
            sheet = wbXlsx.getSheetAt(0);
            Row row = sheet.getRow(3);
            Cell cell = row.getCell(1);

            try {
                // convert String dd-mm-yyyy naar Date yyyy-mm-dd 
                String excelDatum1 = cell.getStringCellValue();
                Date date = new SimpleDateFormat("dd-MM-yyyy").parse(excelDatum1);
                this.excelDatum = this.formatter.format(date);
            } catch (Exception e) {
                double date1 = cell.getNumericCellValue();
                //convert excel double naar datum
                Date date2 = DateUtil.getJavaDate((double) date1);
                this.excelDatum = new SimpleDateFormat("yyyy-MM-dd").format(date2);
            }
            //Iterate through each rows one by one
            rowIterator = sheet.iterator();
        } else {
            HSSFWorkbook wbXls = new HSSFWorkbook(file);
            sheet1 = wbXls.getSheetAt(0);
            Row row = sheet1.getRow(3);
            Cell cell = row.getCell(1);

            // convert String dd-mm-yyyy naar Date yyyy-mm-dd 
            try {
                String excelDatum1 = cell.getStringCellValue();
                Date date = new SimpleDateFormat("dd-MM-yyyy").parse(excelDatum1);
                this.excelDatum = this.formatter.format(date);
            } catch (Exception e) {
                double date1 = cell.getNumericCellValue();
                //convert excel double naar datum
                Date date2 = DateUtil.getJavaDate((double) date1);
                this.excelDatum = new SimpleDateFormat("yyyy-MM-dd").format(date2);
            }
            //Iterate through each rows one by one
            rowIterator = sheet1.iterator();
        }

        //Iterate through each rows one by one
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            //skip first 5 rows
            if (row.getRowNum() == 0 || row.getRowNum() == 1 || row.getRowNum() == 2 || row.getRowNum() == 3
                    || row.getRowNum() == 4) {
                continue;
            }

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

            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                //Check the cell type and format accordingly
                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:
                    //                            System.out.print(cell.getNumericCellValue() + "\t");
                    break;
                case Cell.CELL_TYPE_STRING:
                    //                            System.out.print(cell.getStringCellValue() + "\t");
                    break;
                case Cell.CELL_TYPE_BLANK:
                    //                            System.out.print(cell.getStringCellValue() + "\t");
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    //                            System.out.print(cell.getStringCellValue() + "\t");
                    break;
                }
            }
            // Tabel client
            int kaartnummer = (int) row.getCell(0).getNumericCellValue();
            String naam = row.getCell(1).getStringCellValue();
            String naamPartner = row.getCell(2).getStringCellValue();
            String telefoonnummer = row.getCell(3).getStringCellValue();
            String email = row.getCell(4).getStringCellValue();
            String mobiel = row.getCell(5).getStringCellValue();
            int aantalPersonen = (int) row.getCell(6).getNumericCellValue();
            int aantalPersonenInDeNorm = (int) row.getCell(7).getNumericCellValue();
            double gebruikInMaanden = (double) row.getCell(8).getNumericCellValue();
            String idSoort = row.getCell(9).getStringCellValue();
            //convert excel double naar datum
            double datumUitgifteId1 = row.getCell(10).getNumericCellValue();
            if (datumUitgifteId1 == 0.0) {
                this.datumUitgifteId = null;
            } else {
                Date datumUitgifteId2 = DateUtil.getJavaDate((double) datumUitgifteId1);
                this.datumUitgifteId = new SimpleDateFormat("yyyy-MM-dd").format(datumUitgifteId2);
            }
            ////////////////////////////////////////////////////////////////////////////////////
            String idNummer = row.getCell(11).getStringCellValue();
            String plaatsUitgifteId = row.getCell(12).getStringCellValue();
            String adres = row.getCell(13).getStringCellValue();
            String postcode = row.getCell(14).getStringCellValue();
            String plaats = row.getCell(15).getStringCellValue();
            String status = row.getCell(16).getStringCellValue();

            // Tabel intake
            // kaartnummer gaat hier ook in de query
            String intaker = row.getCell(17).getStringCellValue();
            double intakeDatum1 = row.getCell(18).getNumericCellValue();
            //convert excel double naar datum
            Date intakeDatum2 = DateUtil.getJavaDate((double) intakeDatum1);
            String intakeDatum = new SimpleDateFormat("yyyy-MM-dd").format(intakeDatum2);
            /////////////////////////////////////////////////////////////////////////
            double startDatumUitgifte1 = row.getCell(19).getNumericCellValue();
            //convert excel double naar datum
            Date startDatumUitgifte2 = DateUtil.getJavaDate((double) startDatumUitgifte1);
            String startDatumUitgifte = new SimpleDateFormat("yyyy-MM-dd").format(startDatumUitgifte2);
            //////////////////////////////////////////////////////////////////////////////////
            double datumHerintake1 = row.getCell(20).getNumericCellValue();
            //convert excel double naar datum
            Date datumHerintake2 = DateUtil.getJavaDate((double) datumHerintake1);
            String datumHerintake = new SimpleDateFormat("yyyy-MM-dd").format(datumHerintake2);
            /////////////////////////////////////////////////////////////////////////////////
            // Tabel Stopt
            double datumStopzetting1 = row.getCell(21).getNumericCellValue();
            //convert excel numbers naar datum
            Date datumStopzetting2 = DateUtil.getJavaDate((double) datumStopzetting1);
            String datumStopzetting = new SimpleDateFormat("yyyy-MM-dd").format(datumStopzetting2);
            //////////////////////////////////////////////////////////////////////////////////////
            String redenStopzetting = row.getCell(22).getStringCellValue();

            // Tabel verwijzer
            String verwijzerNaam = row.getCell(23).getStringCellValue();
            String verwijzersDoorContactpersoon1 = row.getCell(24).getStringCellValue();
            String verwijzersDoorContactpersoon = verwijzersDoorContactpersoon1.toLowerCase();
            String verwijzersDoorTelefoonnummer = row.getCell(25).getStringCellValue();
            String verwijzersDoorEmail = row.getCell(26).getStringCellValue();
            String verwijzersNaar = row.getCell(27).getStringCellValue();
            String verwijzersNaarContactpersoon = row.getCell(28).getStringCellValue();
            String verwijzersNaarTelefoonnummer = row.getCell(29).getStringCellValue();
            String verwijzersNaarEmail = row.getCell(30).getStringCellValue();

            // Uitgiftepunt gaat in de tabel intake
            String uitgiftepunt = row.getCell(31).getStringCellValue();

            // PakketSoort gaat in de tabel client
            String pakketSoort = row.getCell(32).getStringCellValue();

            // Query's om de excelsheet in de database te krijgen
            SQLExcelSheetInsert excelSQL = new SQLExcelSheetInsert();
            SQLget getSQL = new SQLget();

            // Losse query uit de tabel om bepaalde gegevens te krijgen om te controleren of die al bestaat of niet
            int Verwijzer = getSQL.getVerwijzernr(verwijzerNaam, verwijzersDoorContactpersoon);
            int checkKaartnr = getSQL.getCheckKaartnummer(kaartnummer);
            int checkUitgiftepunt = getSQL.getUitgiftepunt(uitgiftepunt);

            if (Verwijzer == 0) {
                excelSQL.insertExcelVerwijzer(verwijzerNaam, verwijzersDoorContactpersoon,
                        verwijzersDoorTelefoonnummer, verwijzersDoorEmail, verwijzersNaar,
                        verwijzersNaarContactpersoon, verwijzersNaarTelefoonnummer, verwijzersNaarEmail);
            }

            if (checkUitgiftepunt == 0) {
                int maxVolgorde = getSQL.getCheckVolgordeLijst();
                excelSQL.insertUitgiftepunt(uitgiftepunt, maxVolgorde);
            }

            int Verwijzer2 = getSQL.getVerwijzernr(verwijzerNaam, verwijzersDoorContactpersoon);

            /// Wanneer er geen kaartnummer is die bekend gaat die door naar insert
            if (checkKaartnr == 0) {
                // Wanneer kaartnummer alles behalve 0 is insert die
                if (kaartnummer > 0) {
                    excelSQL.insertExcelClient(kaartnummer, naam, naamPartner, telefoonnummer, email, mobiel,
                            aantalPersonen, aantalPersonenInDeNorm, gebruikInMaanden, idSoort,
                            this.datumUitgifteId, idNummer, plaatsUitgifteId, adres, postcode, plaats, status,
                            pakketSoort, Verwijzer2);
                } else {
                    break;
                }
            } else {
                excelSQL.updateExcelClient(kaartnummer, naam, naamPartner, telefoonnummer, email, mobiel,
                        aantalPersonen, aantalPersonenInDeNorm, gebruikInMaanden, idSoort, this.datumUitgifteId,
                        idNummer, plaatsUitgifteId, adres, postcode, plaats, status, pakketSoort, Verwijzer2);
            }

            int checkIntake = getSQL.getCheckIntake(intakeDatum, startDatumUitgifte, datumHerintake,
                    kaartnummer);

            if (checkIntake == 0) {
                excelSQL.insertExcelIntake(intaker, intakeDatum, startDatumUitgifte, datumHerintake,
                        kaartnummer, uitgiftepunt);
                int intakeId = getSQL.getIntakeId(kaartnummer);
                excelSQL.insertExcelStopt(datumStopzetting, redenStopzetting, intakeId);
            }

            // Kan upgedate worden aan een knop voor een query aan status in de table voedselpakket wel of niet opgehaald
            String status1 = null;

            String checkStatus = getSQL.getStatus(kaartnummer);
            this.pakketAantal = getSQL.getPakketAantal(kaartnummer);
            int intakeId = getSQL.getIntakeId(kaartnummer);
            int checkPakket = getSQL.getPakket(this.excelDatum, intakeId);

            if (checkPakket == 0) {
                if (checkStatus != null) {
                    if (checkStatus.equals("Actief")) {
                        int intakeId2 = getSQL.getIntakeId(kaartnummer);
                        excelSQL.insertVoedselpakket(this.excelDatum, this.pakketAantal, status1, intakeId2,
                                uitgiftepunt);
                    }
                }
            }
        }
        file.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ExampleClass.java

public static void main(String[] args) throws Exception {
    File src = new File(
            "C:\\Users\\Ariq\\Documents\\NetBeansProjects\\Skripsi-Jadwal-Mengawas-Ujian\\Contoh File\\Jadwal_Pengawas_ Ujian_Pak_ Pascal.xlsx");
    //File src = new File("D:\\\\Skripsi\\\\Data Baru\\\\Daftar Dosen.xlsx");
    FileInputStream fis = new FileInputStream(src);
    XSSFWorkbook wb = new XSSFWorkbook(fis);

    XSSFSheet sheet1 = wb.getSheetAt(0);
    //        Iterator< Row> rowIterator = sheet1.iterator();
    int colIndex = 0;
    int ex = 0;/* www .j a  v  a2s .c  o m*/
    int lastCol = sheet1.getLastRowNum();
    int i = 0;
    int idx = 0;
    CellRangeAddress add;

    //        while (rowIterator.hasNext()) {
    //            row = (XSSFRow) rowIterator.next();
    //            Iterator< Cell> cellIterator = row.cellIterator();
    //            //System.out.println("i = "+i+", ex:"+ex);
    //
    //            if (row.getRowNum() > 53) {
    //                break;
    //            }
    ////            if(lastCol-(ex+1) == i) break;
    //            while (cellIterator.hasNext()) {
    //                Cell cell = cellIterator.next();

    //                for (int f = 0; f < sheet1.getNumMergedRegions(); f++) {
    //                    add = sheet1.getMergedRegion(f);
    //                    
    //                    int col = add.getFirstColumn();
    //                    int rowNum = add.getFirstRow();
    //                    if (rowNum != 0 && rowNum == cell.getRowIndex() && colIndex == cell.getColumnIndex()) {
    //                        System.out.println("col:"+col+" "+",row :"+rowNum);
    //                        String b = String.valueOf(sheet1.getRow(rowNum).getCell(col));
    //                        System.out.println(b);     
    //                        
    //                    }
    //                    
    //                }
    //               switch (cell.getCellType()) 
    //               {
    //                  case Cell.CELL_TYPE_FORMULA:
    //                      ex++;
    //                       switch (cell.getCachedFormulaResultType()) 
    //                       {
    //                           case Cell.CELL_TYPE_NUMERIC:
    //                           i = (int)cell.getNumericCellValue();
    //                           System.out.print( 
    //                           (int)cell.getNumericCellValue() + " \t\t " );
    //                             
    //                                 
    //                           break;
    //                       }
    //                   break;
    //                  case Cell.CELL_TYPE_NUMERIC:
    //                    if (cell.getColumnIndex() >= 6)
    //                    {
    //                        System.out.print( 
    //                        (int)cell.getNumericCellValue() + " \t\t " );
    //                    }
    //                    break;
    //                  case Cell.CELL_TYPE_STRING:
    //                   add = sheet1.getMergedRegion(cell.getRowIndex());
    //              
    //                   if (cell.getStringCellValue().contentEquals("No."))
    //                    {
    //                       colIndex = cell.getColumnIndex();
    //                    }
    //                   if (cell.getColumnIndex() == 1)
    //                   {
    //                        System.out.print(
    //                        cell.getStringCellValue() + " \t\t " );
    //                   }              
    //                   break;
    //                  
    //               }
    //            }
    //
    //            System.out.println();
    //        }

    for (int j = 0; j < sheet1.getLastRowNum(); j++) {

        row = sheet1.getRow(j);
        for (int k = 0; k < row.getLastCellNum(); k++) {

            Cell cell = row.getCell(k);
            //                if (cell.getColumnIndex() == 1)
            //                {
            //                    System.out.println(cell.getStringCellValue());
            //                }
            FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
            if (cell.getColumnIndex() == 0 && j > 3
                    && evaluator.evaluate(cell).getCellType() != Cell.CELL_TYPE_NUMERIC) {
                System.exit(k);
            }
            if (cell.getColumnIndex() >= 6 && cell.getColumnIndex() <= 11) {
                if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                    System.out.print((int) cell.getNumericCellValue() + " ");
                }
                if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                    if (cell.getStringCellValue().contains(":")) {
                        String[] splt = cell.getStringCellValue().split(":");
                        String[] splt2 = splt[1].split(",");
                        for (int l = 0; l < splt2.length; l++) {
                            System.out.println(splt2[l] + "= lab");
                        }
                    }

                    else {
                        CellReference cr = new CellReference(1, cell.getColumnIndex());
                        Row row2 = sheet1.getRow(cr.getRow());
                        Cell c = row2.getCell(cr.getCol());
                        System.out.print(
                                cell.getStringCellValue() + " Ruang =" + (int) c.getNumericCellValue() + " ");
                    }

                }
                if (cell.getCellType() == Cell.CELL_TYPE_BLANK && cell.getRowIndex() > 2) {
                    CellReference cr = new CellReference(cell.getRowIndex() - 1, cell.getColumnIndex());
                    Row row2 = sheet1.getRow(cr.getRow());
                    Cell c = row2.getCell(cr.getCol());
                    CellReference cr2 = new CellReference(1, cell.getColumnIndex());
                    Row row3 = sheet1.getRow(cr2.getRow());
                    Cell c2 = row3.getCell(cr2.getCol());
                    if (c.getStringCellValue().contains(":")) {
                        String[] splt = c.getStringCellValue().split(":");
                        String[] splt2 = splt[1].split(",");
                        for (int l = 0; l < splt2.length; l++) {
                            System.out.println(splt2[l] + "= lab");
                        }
                    }

                    else {
                        System.out.print(
                                c.getStringCellValue() + " Ruang = " + (int) c2.getNumericCellValue() + " ");
                    }
                }
            }

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

    System.out.println(idx);

    fis.close();
}

From source file:xlsxtocsv.java

static void convertToXlsx(File inputFile, File outputFile) {
    // For storing data into CSV files
    StringBuffer cellValue = new StringBuffer();
    try {//from  w ww.jav  a2 s .  co  m
        FileOutputStream fos = new FileOutputStream(outputFile);

        // Get the workbook instance for XLSX file
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(inputFile));

        // 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();

        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_BOOLEAN:
                    cellValue.append(cell.getBooleanCellValue() + ",");
                    break;

                case Cell.CELL_TYPE_NUMERIC:
                    cellValue.append(cell.getNumericCellValue() + ",");
                    break;

                case Cell.CELL_TYPE_STRING:
                    cellValue.append(cell.getStringCellValue() + ",");
                    break;

                case Cell.CELL_TYPE_BLANK:
                    cellValue.append("" + ",");
                    break;

                default:
                    cellValue.append(cell + ",");

                }
            }

            cellValue.append("\n");
        }

        fos.write(cellValue.toString().getBytes());
        fos.close();

    } catch (Exception e) {
        System.err.println("Exception :" + e.getMessage());
    }
}

From source file:xlsxtocsv.java

static void convertToXls(File inputFile, File outputFile) {
    // For storing data into CSV files
    StringBuffer cellDData = new StringBuffer();
    try {//from  w  w  w .  j av  a2 s .c om
        FileOutputStream fos = new FileOutputStream(outputFile);

        // Get the workbook instance for XLS file
        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inputFile));
        // Get first sheet from the workbook
        HSSFSheet sheet = workbook.getSheetAt(0);
        Cell cell;
        Row row;

        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();
        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_BOOLEAN:
                    cellDData.append(cell.getBooleanCellValue() + ",");
                    break;

                case Cell.CELL_TYPE_NUMERIC:
                    cellDData.append(cell.getNumericCellValue() + ",");
                    break;

                case Cell.CELL_TYPE_STRING:
                    cellDData.append(cell.getStringCellValue() + ",");
                    break;

                case Cell.CELL_TYPE_BLANK:
                    cellDData.append("" + ",");
                    break;

                default:
                    cellDData.append(cell + ",");
                }
            }

            cellDData.append("\n");
        }

        fos.write(cellDData.toString().getBytes());
        fos.close();

    } catch (FileNotFoundException e) {
        System.err.println("Exception" + e.getMessage());
    } catch (IOException e) {
        System.err.println("Exception" + e.getMessage());
    }
}

From source file:TaskFetcher.java

static HashMap<String, String> fetchActiveTasks(String username, String excel_path) {
    HashMap<String, String> activetasks = new HashMap<String, String>();
    FileInputStream file = null;/*from  w w w.  j  av  a 2 s.c o  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/desired sheet from the workbook
    XSSFSheet sheet = workbook.getSheetAt(0);
    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 totTimeString = null;
            String latestTimeStamp;
            double totTime;
            task = row.getCell(1).getStringCellValue();
            status = row.getCell(2).getStringCellValue();
            latestTimeStamp = row.getCell(3).getStringCellValue();
            if (status.equalsIgnoreCase("Paused") || status.equalsIgnoreCase("Deferred")) {
                if (row.getCell(4) != null)
                    totTimeString = row.getCell(4).getStringCellValue();
            } else if (status.equalsIgnoreCase("In-Progress")) {
                if (row.getCell(4) != null)
                    totTimeString = row.getCell(4).getStringCellValue();
                if (totTimeString != null) {
                    totTime = Double.parseDouble(totTimeString);
                } else {
                    totTime = 0;
                }
                DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
                Date currentTimestamp = new Date();
                Date latestTimeStampObj = null;
                df.format(currentTimestamp);
                try {
                    latestTimeStampObj = df.parse(latestTimeStamp);
                } catch (ParseException ex) {
                    Logger.getLogger(TaskFetcher.class.getName()).log(Level.SEVERE, null, ex);
                }
                long timeDifference = currentTimestamp.getTime() - latestTimeStampObj.getTime();
                long divisor = 60 * 60 * 1000;
                double diffHours = ((double) timeDifference / (double) divisor);
                totTime += diffHours;
                totTimeString = String.valueOf(totTime);
            }
            if (status != null && !status.equalsIgnoreCase("completed") && task != null
                    && totTimeString != null) {
                activetasks.put(task, status + ":" + totTimeString);
            }
        }
    }
    try {
        workbook.close();
    } catch (IOException ex) {
        Logger.getLogger(TaskFetcher.class.getName()).log(Level.SEVERE, null, ex);
    }
    return activetasks;
}