POI:在向数据库插入值时不迭代所有excel行

时间:2015-07-30 10:01:40

标签: java mysql apache-poi derby

我编写了从excel表中读取数据的代码,将数据插入到数据库中。我可以成功读取所有数据,但是当将值发布到数据库时,只发布了一行。这是我写的代码,请帮助。

    private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {                                         

    try {
    FileInputStream file = new FileInputStream(new File("new.xls"));
    org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);
    org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
    Iterator<Row> rowIterator = sheet.iterator();
    rowIterator.next();
    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();
            //This will change all Cell Types to String
            cell.setCellType(Cell.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:


                                             break;
            }
        }
        QT=row.getCell(0).getStringCellValue();
        QG=row.getCell(1).getStringCellValue();
        Mgr=row.getCell(2).getStringCellValue();
        TAP=row.getCell(3).getStringCellValue();
        Prof = row.getCell(4).getStringCellValue();
        CS=row.getCell(5).getStringCellValue();
        SS=row.getCell(6).getStringCellValue();
        SW=row.getCell(7).getStringCellValue();
        PMO=row.getCell(8).getStringCellValue();
        EO=row.getCell(9).getStringCellValue();
        Learner=row.getCell(10).getStringCellValue();
        TTP=row.getCell(11).getStringCellValue();
        System.out.println(QT+QG+Mgr+TAP+Prof+CS+SS+SW+PMO+EO+Learner+TTP);
        System.out.println("");
    }
    file.close();

到此为止,我可以成功读取所有6行并将其显示到控制台。但是将值保存到数据库的代码只保存了一行而不是6行。

    PreparedStatement pst = null;
try{
    Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
    Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
    String sql="Insert into APP.WSP(QUALIFICATIONTYPE ,QUALIFICATIONGROUP ,MANAGERS ,PROFESSIONALS,"+
            "TECHNICIANSASSOCIATEPROFESSIONALS,CLERICALSUPPORT,SERVICESALES,SKILLEDWORKERS,PLANTMACHINEOPERATORS,"+
            "ELEMENTARYOCCUPATION,LEARNERS,TOTALTRAININGPLANNED)"+
            "values(?,?,?,?,?,?,?,?,?,?,?,?)";
    pst =   con.prepareStatement(sql);
    pst.setString(1, QT);
    pst.setString(2, QG);
    pst.setString(3, Mgr);
    pst.setString(4, TAP);
    pst.setString(5, Prof);
    pst.setString(6, CS);
    pst.setString(7, SS);
    pst.setString(8, SW);
    pst.setString(9, PMO);
    pst.setString(10, EO);
    pst.setString(11, Learner);
    pst.setString(12, TTP);
    pst.executeUpdate();
    updateTable();
JOptionPane.showMessageDialog(null,"Values Inserted Successfully");
    }
catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
}
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}   catch (InvalidFormatException ex) {
        Logger.getLogger(OFO.class.getName()).log(Level.SEVERE, null, ex);
    } catch (EncryptedDocumentException ex) {
        Logger.getLogger(OFO.class.getName()).log(Level.SEVERE, null, ex);
    }

1 个答案:

答案 0 :(得分:1)

好的,按要求。代码未经过测试,可能仍会存在一些错误。

请注意

  • 您不需要再调用Class.forName()来加载数据库驱动程序(请参阅有关DriverManager的介绍段落。)

  • 您应该使用try-with-resources来使代码更健壮,更易于维护

  • 重复使用您准备好的陈述

  • 请使用DataFormatter将单元格值作为文本(或者更好地在SQL中使用正确的类型)

代码:

private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {
    // the SQL INSERT statement
    String sql="Insert into APP.WSP(QUALIFICATIONTYPE ,QUALIFICATIONGROUP ,MANAGERS ,PROFESSIONALS,"+
            "TECHNICIANSASSOCIATEPROFESSIONALS,CLERICALSUPPORT,SERVICESALES,SKILLEDWORKERS,PLANTMACHINEOPERATORS,"+
            "ELEMENTARYOCCUPATION,LEARNERS,TOTALTRAININGPLANNED)"+
            "values(?,?,?,?,?,?,?,?,?,?,?,?)";

    // use try-with resources!
    // BTW: Class.forName() is no more required for properly installed drivers in Java 7
    try (FileInputStream file = new FileInputStream("new.xls");
         Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
         PreparedStatement pst = con.prepareStatement(sql)) {

        // create workbook
        org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);
        org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();

        // skip the first line (headline)
        rowIterator.next(); 

        // use this to retrieve Strings from numeric cells
        DataFormatter df = new DataFormatter();

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

            // get cell values
            QT=df.formatCellValue(row.getCell(0));
            QG=df.formatCellValue(row.getCell(1));
            Mgr=df.formatCellValue(row.getCell(2));
            TAP=df.formatCellValue(row.getCell(3));
            Prof =df.formatCellValue(row.getCell(4));
            CS=df.formatCellValue(row.getCell(5));
            SS=df.formatCellValue(row.getCell(6));
            SW=df.formatCellValue(row.getCell(7));
            PMO=df.formatCellValue(row.getCell(8));
            EO=df.formatCellValue(row.getCell(9));
            Learner=df.formatCellValue(row.getCell(10));
            TTP=df.formatCellValue(row.getCell(11));

            // print to console
            System.out.println(QT+QG+Mgr+TAP+Prof+CS+SS+SW+PMO+EO+Learner+TTP);
            System.out.println("");

            // write to database
            pst.setString(1, QT);
            pst.setString(2, QG);
            pst.setString(3, Mgr);
            pst.setString(4, TAP);
            pst.setString(5, Prof);
            pst.setString(6, CS);
            pst.setString(7, SS);
            pst.setString(8, SW);
            pst.setString(9, PMO);
            pst.setString(10, EO);
            pst.setString(11, Learner);
            pst.setString(12, TTP);
            pst.executeUpdate();        
        }

        // what does this do?
        updateTable(); 

        // show success dialog
        JOptionPane.showMessageDialog(null,"Values Inserted Successfully");
    } catch(Exception e){
        // Show error dialog
        JOptionPane.showMessageDialog(null, e);
    }
}