Example usage for org.apache.poi.xssf.usermodel XSSFSheet iterator

List of usage examples for org.apache.poi.xssf.usermodel XSSFSheet iterator

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFSheet iterator.

Prototype

@Override
public Iterator<Row> iterator() 

Source Link

Document

Alias for #rowIterator() to allow foreach loops

Usage

From source file:service.Read_Write_File.java

public static List<Consomation> Read_Fil_XLSX(File myFile) throws FileNotFoundException, IOException {
    List<CorpDetat> corpDetats = new ArrayList<CorpDetat>();
    List<Consomation> consomations = new ArrayList<Consomation>();

    FileInputStream fis = new FileInputStream(myFile);

    XSSFWorkbook myWorkBook = new XSSFWorkbook(fis);

    XSSFSheet mySheet = myWorkBook.getSheetAt(0);

    Iterator<Row> rowIterator = mySheet.iterator();

    Consomation consomation = null;//from  w w w  .  j  a  v a  2s.  com
    CorpDetat corpDetat = null;
    ConsomationItem consomationItem = null;
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        if (row.getRowNum() == 0) {// pour ne pas lire les  titres
            row = rowIterator.next();
        }

        int lascellNum = row.getLastCellNum();
        int firstcellNum = row.getFirstCellNum();
        System.out.println("first cell num" + firstcellNum + "  last cell num" + lascellNum);
        if (lascellNum < 3) {
            if (row.getRowNum() > 1) {
                //corpDetats.add(corpDetat);

                consomations.add(consomation);
                corpDetat = null;
                System.out.println("if dyal row celll");
            }
            consomation = new Consomation();
            consomation.setId((int) row.getCell(firstcellNum).getNumericCellValue());
            corpDetat = new CorpDetat();
            corpDetat.setTitre(row.getCell(firstcellNum + 1).getStringCellValue());

        } else {
            Post post = new Post();
            consomationItem = new ConsomationItem();

            for (int i = firstcellNum; i < lascellNum; i++) {
                Cell cell = row.getCell(i);

                switch (i) {
                case 0:
                    System.out.println("num de consomation item" + cell.getStringCellValue());
                    consomationItem.setId(cell.getStringCellValue());
                    break;
                case 1:
                    System.out.println("cell " + i + ":" + cell.getStringCellValue());
                    post.setTitre(cell.getStringCellValue());
                    break;
                case 2:
                    consomationItem.setUnite(cell.getStringCellValue());
                    break;
                case 3:
                    System.out.println("cell " + i + ":" + cell.getCellType());
                    consomationItem.setQuanite((int) cell.getNumericCellValue());
                    break;

                }
            }
            if (post != null) {
                post.setCorpdetat(corpDetat);
                consomationItem.setPost(post);
                post.setCorpdetat(corpDetat);
                corpDetat.getPosts().add(post);
                consomation.getConsomationItems().add(consomationItem);
                consomation.setCorpDetat(corpDetat);

            }
        }

    }

    consomations.add(consomation);
    // pour le dernier corp makydkholch l row li tab30

    return consomations;
}

From source file:som.file.StemmedDataFileReader.java

License:Open Source License

public void writeIntoInputDataSheet(List<String> wordsList) {
    XSSFWorkbook workbook = null;/*from w w w .j a  va  2s. com*/
    try {
        System.out.println("Writing into Input File");
        FileInputStream file = new FileInputStream(
                new File(GenericHelper.getAbsolutePath() + REVISED_INPUT_SHEET_NAME));
        //FileInputStream file = new FileInputStream(new File(REVISED_INPUT_SHEET_NAME));
        //File file = new File(REVISED_INPUT_SHEET_NAME);

        //Get the workbook instance for XLS file 
        workbook = new XSSFWorkbook(file);

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

        //Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            if (row.getRowNum() == 0) {
                continue;
            }

            Cell cell = row.getCell(IGenericConstants.STEMMED_DATA_COLUMN_NUMBER);
            if (wordsList.size() > row.getRowNum()) {
                cell.setCellValue(wordsList.get(row.getRowNum()));
            }
        }

        file.close();

        System.out.println("Writing to the file on the server");
        FileOutputStream outFile = new FileOutputStream(
                new File(GenericHelper.getAbsolutePath() + REVISED_INPUT_SHEET_NAME));
        workbook.write(outFile);
        System.out.println("File Writing Complete");
        outFile.close();

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

From source file:temp.ExcelReader.java

public static void readFromXLSXFile(File file) {
    try {//from  w w  w . j a va2  s . co  m
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));

        int sheetCount = workbook.getNumberOfSheets();

        System.out.println(sheetCount);

        XSSFSheet sheet = workbook.getSheetAt(0);

        Iterator<Row> rowItertor = sheet.iterator();

        while (rowItertor.hasNext()) {
            Row row = rowItertor.next();

            for (int i = 0; i < row.getLastCellNum(); i++) {
                System.out.print(row.getCell(i) + "|"); //this you won't miss any cells! right way to do
            }

            System.out.println("");

        }

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

From source file:Test.LeerExcelXlsx.java

public static void main(String args[]) throws IOException {
    FileInputStream file = new FileInputStream(
            new File("C:\\Users\\f2 a55m-s1\\Documents\\baseSqlLite\\Libro1.xlsx"));
    // Crear el objeto que tendra el libro de Excel
    XSSFWorkbook workbook = new XSSFWorkbook(file);

    /*/* www. j  av a  2  s  . com*/
     * Obtenemos la primera pestaa a la que se quiera procesar indicando el indice.
     * Una vez obtenida la hoja excel con las filas que se quieren leer obtenemos el iterator
     * que nos permite recorrer cada una de las filas que contiene.
     */
    XSSFSheet sheet = workbook.getSheetAt(0);
    Iterator<Row> rowIterator = sheet.iterator();

    Row row;
    // Recorremos todas las filas para mostrar el contenido de cada celda
    while (rowIterator.hasNext()) {
        row = rowIterator.next();

        // Obtenemos el iterator que permite recorres todas las celdas de una fila
        Iterator<Cell> cellIterator = row.cellIterator();
        Cell celda;

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

            // Dependiendo del formato de la celda el valor se debe mostrar como String, Fecha, boolean, entero...
            switch (celda.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(celda)) {
                    System.out.print(celda.getDateCellValue());
                } else {
                    System.out.print(celda.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_STRING:
                System.out.print(celda.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                System.out.print(celda.getBooleanCellValue());
                break;
            }
        }
        System.out.println("");
    }

    // cerramos el libro excel
    workbook.close();
}

From source file:testpoi.OPDDataTransfer.java

License:Open Source License

public static void main(String args[]) {
    try {/*w ww  .j  a v a2s.  co m*/
        String dateFolder = "2.3.13";

        FileInputStream file = new FileInputStream(
                new File("C:\\Documents and Settings\\Admin\\My Documents\\NetBeansProjects\\TestPOI\\Docs\\"
                        + dateFolder + "\\" + dateFolder + ".xlsx"));

        //Get the workbook instance for XLS file 
        XSSFWorkbook workbook = new XSSFWorkbook(file);

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

        Connection conn = connectToDatabaseHMS();
        assert (conn != null);
        Connection conn2 = connectToDatabaseHMSSecurity();
        assert (conn2 != null);

        try {
            conn.setAutoCommit(false);
            conn2.setAutoCommit(false);
        } catch (SQLException sqle) {
            System.err.println("Could not set autocommit to false");
            sqle.printStackTrace();
        }

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

        //Skip the 1st row
        rowIterator.next();

        //set time
        time = Time.valueOf("09:00:00");
        //set entry number default to 1.
        entryNumber = 1;
        //            //set entry crNo
        //            entryCrNo = 1;
        Timestamp timestamp = new Timestamp(date.getTime() + time.getTime() + 19800000/*for IST*/);
        System.out.println(timestamp.toString());

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

            //For each row, get values of each column
            Iterator<Cell> cellIterator = row.cellIterator();
            //                Cell cell = cellIterator.next();
            //                int crNo;
            //                if(cell.getCellType()==0)
            //                     crNo = (int)(cell.getNumericCellValue());
            //                else
            //                {
            //                    System.out.println ("crNo cell value: "+cell.getStringCellValue());
            //                    crNo = (int)Integer.parseInt(cell.getStringCellValue().trim());
            //                }

            Cell cell = cellIterator.next();
            String dept;
            if (cell.getCellType() == 1)
                dept = cell.getStringCellValue();
            else {
                int no = (int) cell.getNumericCellValue();
                dept = no + "";
                System.out.println(dept);
            }
            cell = cellIterator.next();
            String type = cell.getStringCellValue();
            cell = cellIterator.next();

            int crNo;
            if (cell.getCellType() == 0)
                crNo = (int) (cell.getNumericCellValue());
            else {
                System.out.println("crNo cell value: " + cell.getStringCellValue());
                crNo = (int) Integer.parseInt(cell.getStringCellValue().trim());
            }

            cell = cellIterator.next();
            String name = cell.getStringCellValue();
            cell = cellIterator.next();
            String guardian = cell.getStringCellValue();
            cell = cellIterator.next();
            String rel = cell.getStringCellValue();
            cell = cellIterator.next();
            System.out.println("\n cell.getCellType() :" + cell.getCellType());
            int ageYrs = 0;
            if (cell.getCellType() == 0)
                ageYrs = (int) (cell.getNumericCellValue());
            else {
                System.out.println("age cell value: " + cell.getStringCellValue());
                ageYrs = (int) Integer.parseInt(cell.getStringCellValue().trim());
            }

            cell = cellIterator.next();
            String gender = cell.getStringCellValue();
            cell = cellIterator.next();
            String add = cell.getStringCellValue();
            cell = cellIterator.next();
            String city = cell.getStringCellValue();
            cell = cellIterator.next();
            String state = cell.getStringCellValue();

            int deptID = getDeptID(dept);
            assert (deptID != 0);
            int stateID = getStateID(state);
            assert (stateID != 0);
            int drID = getDrID(deptID);
            assert (drID != 0); // if drID = 0 that means a dept. has been entered which doesn't have a doctor
            String loginUserName = getLoginUserName();
            String userID = getLoginUserID(loginUserName);

            long OPDNo = Long.parseLong(OPDDATE + entryNumber);

            boolean queryExecuted = true;
            if (type.equals("New")) // As only New patients must be registered and have a CR generated
            {
                try {
                    String insertSql = "INSERT INTO Reg "
                            + "(Regno, Name, Fname, Relation, AgeY, Sex, Address1, City, State, Department, Date)"
                            + "VALUES(" + crNo + ",'" + name + "','" + guardian + "','" + rel + "'," + ageYrs
                            + ",'" + gender + "','" + add + "','" + city + "'," + stateID + "," + deptID + ",'"
                            + date + "')";
                    System.out.println(insertSql);
                    Statement st = conn.createStatement();
                    int val = st.executeUpdate(insertSql);
                    System.out.println("One row in Reg gets affected...");

                } catch (SQLException ex) {
                    queryExecuted = false;
                    System.out.println("Cannot insert row into Reg...!!");
                    ex.printStackTrace();
                }
            }
            try {
                String insertSql = "INSERT INTO OPD "
                        + "(OPDNo, CrNo, PatientType, DepartmentId, DrId, Date, Time, LoginUserName, IsActive)"
                        + "VALUES(" + OPDNo + "," + crNo + ",'" + type + "'," + deptID + "," + drID + ",'"
                        + date + "','" + time + "','" + loginUserName + "','" + true + "')";
                System.out.println(insertSql);
                Statement st = conn.createStatement();
                int val = st.executeUpdate(insertSql);
                System.out.println("One row in OPD gets affected...");
            } catch (SQLException ex) {
                queryExecuted = false;
                System.out.println("Cannot insert row into OPD...!!");
                ex.printStackTrace();
            }

            try {
                String updateSql = "UPDATE aspnet_Users " + "SET LastActivityDate='" + timestamp + "'"
                        + "WHERE UserId='" + userID + "'";
                System.out.println(updateSql);
                Statement st = conn2.createStatement();
                int val = st.executeUpdate(updateSql);
                System.out.println("One row in aspnet_Users gets affected...");
            } catch (SQLException ex) {
                queryExecuted = false;
                System.out.println("Cannot update timestamp in aspnet_Users...!!");
                ex.printStackTrace();
            }

            if (!queryExecuted)
                //if insertion to any table fails, rollback.
                try {
                    conn.rollback();
                    conn2.rollback();

                    break; // and run program again at any error
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            else
                try {
                    conn.commit();
                    conn2.commit();

                    entryNumber++;
                    //                        entryCrNo++;
                    time = new Time(time.getTime() + 50000);//add 50 seconds
                    timestamp = new Timestamp(timestamp.getTime() + 50000);
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }

        }
        file.close();

        if (conn != null) {
            try {
                // close() releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.
                conn.close();
                System.out.println("HMS Database connection terminated...!!!");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        if (conn2 != null) {
            try {
                // close() releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.
                conn2.close();
                System.out.println("HMS_Security Database connection terminated...!!!");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

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

From source file:testpoi.POIFeed2Tables.java

License:Open Source License

public static void main(String args[]) {
    try {//from w ww  .  ja v a  2s  .  c  o m

        FileInputStream file = new FileInputStream(new File(
                "C:\\Documents and Settings\\Admin\\My Documents\\NetBeansProjects\\TestPOI\\Docs\\1.xlsx"));

        //Get the workbook instance for XLS file 
        XSSFWorkbook workbook = new XSSFWorkbook(file);

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

        Connection conn = connectToDatabase();
        assert (conn != null);

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

        //Skip the 1st row
        rowIterator.next();

        //set time
        time = Time.valueOf("09:00:00");
        //set entry number default to 1.
        entryNumber = 1;
        //set entry crNo
        entryCrNo = 1;

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

            //For each row, get values of each column
            Iterator<Cell> cellIterator = row.cellIterator();
            Cell cell = cellIterator.next();
            int crNo;
            if (cell.getCellType() == 0)
                crNo = (int) (cell.getNumericCellValue());
            else {
                System.out.println("crNo cell value: " + cell.getStringCellValue());
                crNo = (int) Integer.parseInt(cell.getStringCellValue().trim());
            }

            cell = cellIterator.next();
            String dept;
            if (cell.getCellType() == 1)
                dept = cell.getStringCellValue();
            else {
                int no = (int) cell.getNumericCellValue();
                dept = no + "";
                System.out.println(dept);
            }
            cell = cellIterator.next();
            String name = cell.getStringCellValue();
            cell = cellIterator.next();
            String guardian = cell.getStringCellValue();
            cell = cellIterator.next();
            String rel = cell.getStringCellValue();
            cell = cellIterator.next();
            System.out.println("\n cell.getCellType() :" + cell.getCellType());
            int ageYrs = 0;
            if (cell.getCellType() == 0)
                ageYrs = (int) (cell.getNumericCellValue());
            else {
                System.out.println("age cell value: " + cell.getStringCellValue());
                ageYrs = (int) Integer.parseInt(cell.getStringCellValue().trim());
            }

            cell = cellIterator.next();
            String gender = cell.getStringCellValue();
            cell = cellIterator.next();
            String add = cell.getStringCellValue();
            cell = cellIterator.next();
            String city = cell.getStringCellValue();
            cell = cellIterator.next();
            String state = cell.getStringCellValue();

            int deptID = getDeptID(dept);
            assert (deptID != 0);
            int stateID = getStateID(state);
            assert (stateID != 0);
            int drID = getDrID(deptID);
            assert (drID != 0); // if drID = 0 that means a dept. has been entered which doesn't have a doctor
            String loginUserName = getLoginUserName();

            long OPDNo = Long.parseLong(OPDDATE + entryNumber);

            boolean queryExecuted = true;
            try {
                conn.setAutoCommit(false);
                String insertSql = "INSERT INTO Reg "
                        + "(Regno, Name, Fname, Relation, AgeY, Sex, Address1, City, State, Department, Date)"
                        + "VALUES(" + crNo + ",'" + name + "','" + guardian + "','" + rel + "'," + ageYrs + ",'"
                        + gender + "','" + add + "','" + city + "'," + stateID + "," + deptID + ",'" + date
                        + "')";
                System.out.println(insertSql);
                Statement st = conn.createStatement();
                int val = st.executeUpdate(insertSql);
                System.out.println("One row in Reg gets affected...");

            } catch (SQLException ex) {
                queryExecuted = false;
                System.out.println("Cannot insert row into Reg...!!");
                ex.printStackTrace();
            }

            try {
                String insertSql = "INSERT INTO OPD "
                        + "(OPDNo, CrNo, PatientType, DepartmentId, DrId, Date, Time, LoginUserName, IsActive)"
                        + "VALUES(" + OPDNo + "," + entryCrNo + ",'NEW'," + deptID + "," + drID + ",'" + date
                        + "','" + time + "','" + loginUserName + "','" + true + "')";
                System.out.println(insertSql);
                Statement st = conn.createStatement();
                int val = st.executeUpdate(insertSql);
                System.out.println("One row in OPD gets affected...");
            } catch (SQLException ex) {
                queryExecuted = false;
                System.out.println("Cannot insert row into OPD...!!");
                ex.printStackTrace();
            }

            if (!queryExecuted)
                //if insertion to any table fails, rollback.
                try {
                    conn.rollback();

                    break; // and run program again at any error
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            else
                try {
                    conn.commit();
                    entryNumber++;
                    entryCrNo++;
                    time = new Time(time.getTime() + 90000);//add 90 seconds
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }

        }
        file.close();

        if (conn != null) {
            try {
                // close() releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.
                conn.close();
                System.out.println("Database connection terminated...!!!");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

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

From source file:testpoi.POI_MySQL_Test.java

License:Open Source License

public static void main(String args[]) {
    try {//from www .  ja  v  a2s .c o  m

        FileInputStream file = new FileInputStream(new File(
                "C:\\Documents and Settings\\Admin\\My Documents\\NetBeansProjects\\TestPOI\\Docs\\OPD_NEW_2.xlsx"));

        //Get the workbook instance for XLS file 
        XSSFWorkbook workbook = new XSSFWorkbook(file);

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

        Connection conn = connectToDatabase();
        assert (conn != null);

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

        //Skip the 1st row
        rowIterator.next();

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

            //For each row, get values of each column
            Iterator<Cell> cellIterator = row.cellIterator();
            Cell cell = cellIterator.next();
            int crNo;
            if (cell.getCellType() == 0)
                crNo = (int) (cell.getNumericCellValue());
            else {
                System.out.println("crNo cell value: " + cell.getStringCellValue());
                crNo = (int) Integer.parseInt(cell.getStringCellValue().trim());
            }

            cell = cellIterator.next();
            String dept;
            if (cell.getCellType() == 1)
                dept = cell.getStringCellValue();
            else {
                int no = (int) cell.getNumericCellValue();
                dept = no + "";
                System.out.println(dept);
            }
            cell = cellIterator.next();
            String name = cell.getStringCellValue();
            cell = cellIterator.next();
            String guardian = cell.getStringCellValue();
            cell = cellIterator.next();
            String rel = cell.getStringCellValue();
            cell = cellIterator.next();
            System.out.println("\n cell.getCellType() :" + cell.getCellType());
            int ageYrs = 0;
            if (cell.getCellType() == 0)
                ageYrs = (int) (cell.getNumericCellValue());
            else {
                System.out.println("age cell value: " + cell.getStringCellValue());
                ageYrs = (int) Integer.parseInt(cell.getStringCellValue().trim());
            }

            cell = cellIterator.next();
            String gender = cell.getStringCellValue();
            cell = cellIterator.next();
            String add = cell.getStringCellValue();
            cell = cellIterator.next();
            String city = cell.getStringCellValue();
            cell = cellIterator.next();
            String state = cell.getStringCellValue();

            try {
                Statement st = conn.createStatement();
                String insertSql = "INSERT INTO OPDData VALUES(" + crNo + ",'" + dept + "','" + name + "','"
                        + guardian + "','" + rel + "'," + ageYrs + ",'" + gender + "','" + add + "','" + city
                        + "','" + state + "')";
                System.out.println(insertSql);
                int val = st.executeUpdate(insertSql);
                System.out.println("One row get affected...");

            } catch (SQLException ex) {
                System.out.println("Cannot connect to database server...!!");
                ex.printStackTrace();
            }
        }
        file.close();

        if (conn != null) {
            try {
                // close() releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.
                conn.close();
                System.out.println("Database connection terminated...!!!");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

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

From source file:testpoi.POI_POC.java

/**
 * @param args the command line arguments
 *///from   ww  w  . j a  v  a  2s.c  om
public static void main(String[] args) {
    try {

        FileInputStream file = new FileInputStream(
                new File("/home/chandni/Documents/HMS Docs/01.01.2014.xlsx"));

        //Get the workbook instance for XLS file 
        XSSFWorkbook 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();

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

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

                Cell cell = cellIterator.next();

                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.print(cell.getBooleanCellValue() + "\t\t");
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    System.out.print(cell.getNumericCellValue() + "\t\t");
                    break;
                case Cell.CELL_TYPE_STRING:
                    System.out.print(cell.getStringCellValue() + "\t\t");
                    break;
                }
            }
            System.out.println("");
        }
        file.close();

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

From source file:testpoi_.OPDDataTransfer.java

License:Open Source License

public static void main(String args[]) {
    try {//from  w  ww  . j av  a2  s .  c  om

        FileInputStream file = new FileInputStream(
                new File("C:\\Documents and Settings\\Admin\\My Documents\\NetBeansProjects\\TestPOI\\Docs\\"
                        + dateFolder + "\\" + dateFolder + ".xlsx"));

        //Get the workbook instance for XLS file 
        XSSFWorkbook workbook = new XSSFWorkbook(file);

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

        Connection conn = connectToDatabaseHMS();
        assert (conn != null);
        Connection conn2 = connectToDatabaseHMSSecurity();
        assert (conn2 != null);

        try {
            conn.setAutoCommit(false);
            conn2.setAutoCommit(false);
        } catch (SQLException sqle) {
            System.err.println("Could not set autocommit to false");
            sqle.printStackTrace();
        }

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

        //Skip the 1st row
        rowIterator.next();

        /*************************** TO UPDATE ON ERROR ******************************/
        //set time
        time = Time.valueOf("09:00:00");
        //set entry number default to 1.
        entryNumber = 1;

        /*****************************************************************************/

        //            //set entry crNo
        //            entryCrNo = 1;
        Timestamp timestamp = new Timestamp(date.getTime() + time.getTime() + 19800000/*for IST*/);
        System.out.println(timestamp.toString());

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

            //For each row, get values of each column
            Iterator<Cell> cellIterator = row.cellIterator();

            Cell cell = cellIterator.next();
            String dept;
            if (cell.getCellType() == 1)
                dept = cell.getStringCellValue();
            else {
                int no = (int) cell.getNumericCellValue();
                dept = no + "";
                System.out.println(dept);
            }
            cell = cellIterator.next();
            String type = cell.getStringCellValue();
            cell = cellIterator.next();

            int crNo;
            if (cell.getCellType() == 0)
                crNo = (int) (cell.getNumericCellValue());
            else {
                System.out.println("crNo cell value: " + cell.getStringCellValue());
                crNo = (int) Integer.parseInt(cell.getStringCellValue().trim());
            }

            cell = cellIterator.next();
            String name = cell.getStringCellValue();
            cell = cellIterator.next();
            String guardian = cell.getStringCellValue();
            cell = cellIterator.next();
            String rel = cell.getStringCellValue();
            cell = cellIterator.next();
            System.out.println("\n cell.getCellType() :" + cell.getCellType());
            int ageYrs = 0;
            if (cell.getCellType() == 0)
                ageYrs = (int) (cell.getNumericCellValue());
            else {
                System.out.println("age cell value: " + cell.getStringCellValue());
                ageYrs = (int) Integer.parseInt(cell.getStringCellValue().trim());
            }

            cell = cellIterator.next();
            String gender = cell.getStringCellValue();
            cell = cellIterator.next();
            String add = cell.getStringCellValue();
            cell = cellIterator.next();
            String city = cell.getStringCellValue();
            cell = cellIterator.next();
            String state = cell.getStringCellValue();

            int deptID = getDeptID(dept);
            assert (deptID != 0);
            int stateID = getStateID(state);
            assert (stateID != 0);
            int drID = getDrID(deptID);
            assert (drID != 0); // if drID = 0 that means a dept. has been entered which doesn't have a doctor
            String loginUserName = getLoginUserName();
            String userID = getLoginUserID(loginUserName);

            long OPDNo = Long.parseLong(OPDDATE + entryNumber);

            boolean queryExecuted = true;
            if (type.equals("New")) // As only New patients must be registered and have a CR generated
            {
                try {
                    String insertSql = "INSERT INTO Reg "
                            + "(Regno, Name, Fname, Relation, AgeY, Sex, Address1, City, State, Department, Date)"
                            + "VALUES(" + crNo + ",'" + name + "','" + guardian + "','" + rel + "'," + ageYrs
                            + ",'" + gender + "','" + add + "','" + city + "'," + stateID + "," + deptID + ",'"
                            + date + "')";
                    System.out.println(insertSql);
                    Statement st = conn.createStatement();
                    int val = st.executeUpdate(insertSql);
                    System.out.println("One row in Reg gets affected...");

                } catch (SQLException ex) {
                    queryExecuted = false;
                    System.out.println("Cannot insert row into Reg...!!");
                    ex.printStackTrace();
                }
            }
            try {
                String insertSql = "INSERT INTO OPD "
                        + "(OPDNo, CrNo, PatientType, DepartmentId, DrId, Date, Time, LoginUserName, IsActive)"
                        + "VALUES(" + OPDNo + "," + crNo + ",'" + type + "'," + deptID + "," + drID + ",'"
                        + date + "','" + time + "','" + loginUserName + "','" + true + "')";
                System.out.println(insertSql);
                Statement st = conn.createStatement();
                int val = st.executeUpdate(insertSql);
                System.out.println("One row in OPD gets affected...");
            } catch (SQLException ex) {
                queryExecuted = false;
                System.out.println("Cannot insert row into OPD...!!");
                ex.printStackTrace();
            }

            try {
                String updateSql = "UPDATE aspnet_Users " + "SET LastActivityDate='" + timestamp + "'"
                        + "WHERE UserId='" + userID + "'";
                System.out.println(updateSql);
                Statement st = conn2.createStatement();
                int val = st.executeUpdate(updateSql);
                System.out.println("One row in aspnet_Users gets affected...");
            } catch (SQLException ex) {
                queryExecuted = false;
                System.out.println("Cannot update timestamp in aspnet_Users...!!");
                ex.printStackTrace();
            }

            if (!queryExecuted)
                //if insertion to any table fails, rollback.
                try {
                    conn.rollback();
                    conn2.rollback();

                    break; // and run program again at any error
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            else
                try {
                    conn.commit();
                    conn2.commit();

                    entryNumber++;
                    //                        entryCrNo++;
                    time = new Time(time.getTime() + 50000);//add 50 seconds
                    timestamp = new Timestamp(timestamp.getTime() + 50000);
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }

        }
        file.close();

        if (conn != null) {
            try {
                // close() releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.
                conn.close();
                System.out.println("HMS Database connection terminated...!!!");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        if (conn2 != null) {
            try {
                // close() releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.
                conn2.close();
                System.out.println("HMS_Security Database connection terminated...!!!");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

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

From source file:Tools.CompareDrotVSRoster.java

public void colorXLSXFile(String leaveXlsxRoster) throws FileNotFoundException, IOException {
    File xlsxFile = new File(leaveXlsxRoster);
    try {/*from w  w  w .j a  v a2  s  . c om*/
        FileInputStream fis = new FileInputStream(xlsxFile);
        XSSFWorkbook myWorkBook = new XSSFWorkbook(fis);

        //Return first sheet from the XLSX workbook
        XSSFSheet mySheet = myWorkBook.getSheetAt(0);

        //Get iterator to all the rows in current sheet
        Iterator<Row> rowIterator = mySheet.iterator();
        // Traversing over each row of XLSX file
        if (rowIterator.hasNext()) {
            Row headerRow = rowIterator.next(); //skip the header row
            Iterator<Cell> it = headerRow.cellIterator();
            int numCell = 0;
            // List<String> keyList = new ArrayList<>(); //keep track info of each column
            while (it.hasNext()) {
                //keyList.add(it.next().getStringCellValue());   
                it.next();
                numCell++;
            }

            if (numCell == GlobalVar.LEAVE_TITLES_V1.length) { // correct xlsx file                 
                int rowNum = 1;
                while (rowIterator.hasNext()) {
                    Row row = rowIterator.next();
                    //row.getRowStyle();
                    rowNum++;
                }
                for (int i = 1; i < rowNum; i++) {
                    Row row = mySheet.getRow(i);
                    foregroundColorSetUpV1(row, myWorkBook); //check each row and update foreground color
                }
                fis.close();
                FileOutputStream output;
                String targetFile = null;
                String[] names = leaveXlsxRoster.split("\\.");
                if (!names[0].equals(leaveXlsxRoster)) { //doesn't contain surfix
                    targetFile = names[0] + "COLORED.xlsx";
                } else {
                    targetFile = leaveXlsxRoster + "COLORED.xlsx";
                }
                output = new FileOutputStream(targetFile);
                myWorkBook.write(output);
                output.close();
                //myWorkBook.write(output);

            } else if (numCell == GlobalVar.LEAVE_TITLES_V2.length) { // full ssn roster
                System.out.println("CompareDrotVsRoster.java: Unsupported.");
                JOptionPane.showMessageDialog(null, "XLSX file doesn't contain correct info! "
                        + "CompareDrotVsRoster.java: Title V2 is not supported");
            } else {
                JOptionPane.showMessageDialog(null, "XLSX file doesn't contain correct info!");
            }
        } else {
            JOptionPane.showMessageDialog(null, "XLSX file is empty!");
            System.out.println("The xlsx file is empty!");
        }
        JOptionPane.showMessageDialog(null,
                "The leave roster is colored successfully. Please check *COLORED.xlsx.");
        // finds the work book in stance for XLSX file
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Xlsx file not found!");
    }

}