使用JAVA将数据从Excel插入到Oracle数据库中

时间:2017-06-23 10:19:52

标签: java

我的Excel工作表中有7列。我在数据库中创建了一个具有相应列名的空表。 那么,如何将Excel中的所有数据插入到数据库表中。 请帮助我,谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用POI执行此操作。示例代码如下所示。有关详细信息,请参阅this

   /* Create Connection objects */
            Class.forName ("oracle.jdbc.OracleDriver"); 
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/xe", "hr", "hr");
            PreparedStatement sql_statement = null;
            String jdbc_insert_sql = "INSERT INTO XLS_POI"
                            + "(KEYWORD, TOTAL_COUNT) VALUES"
                            + "(?,?)";
            sql_statement = conn.prepareStatement(jdbc_insert_sql);
            /* We should now load excel objects and loop through the worksheet data */
            FileInputStream input_document = new FileInputStream(new File("xls_to_oracle.xls"));
            /* Load workbook */
            HSSFWorkbook my_xls_workbook = new HSSFWorkbook(input_document);
            /* Load worksheet */
            HSSFSheet my_worksheet = my_xls_workbook.getSheetAt(0);
            // we loop through and insert data
            Iterator<Row> rowIterator = my_worksheet.iterator(); 
            while(rowIterator.hasNext()) {
                    Row row = rowIterator.next(); 
                    Iterator<Cell> cellIterator = row.cellIterator();
                            while(cellIterator.hasNext()) {
                                    Cell cell = cellIterator.next();
                                    switch(cell.getCellType()) { 
                                    case Cell.CELL_TYPE_STRING: //handle string columns
                                            sql_statement.setString(1, cell.getStringCellValue());                                                                                     
                                            break;
                                    case Cell.CELL_TYPE_NUMERIC: //handle double data
                                            sql_statement.setDouble(2,cell.getNumericCellValue() );
                                            break;
                                    }

                            }
            //we can execute the statement before reading the next row
            sql_statement.executeUpdate();
            }
            /* Close input stream */
            input_document.close();
            /* Close prepared statement */
            sql_statement.close();
            /* COMMIT transaction */
            conn.commit();
            /* Close connection */
            conn.close();