如何从Excel中插入行到MySQL数据库?

我GOOGLE和谷歌search,但无法find一个单一的适当的工作示例,最后我把这个转换为MySQL导入我的情况下,这里是代码:

import java.io.*; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFCell; import java.util.*; import java.sql.*; public class Import { public static void main(String[] args) throws Exception{ /* Create Connection objects */ // Class.forName ("oracle.jdbc.OracleDriver"); Properties connectionProps = new Properties(); connectionProps.put("user", "myUSERNAME"); connectionProps.put("password", "myPASSWORD"); Connection conn = DriverManager.getConnection("jdbc:mysql://" + "serverIP" + ":" + "3306" + "/" + "myDB", connectionProps); PreparedStatement sql_statement = null; String jdbc_insert_sql = "INSERT INTO myTABLE" + "(LastName, FirstName) 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("insert_old.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; } } // Add the row to a batch processing - standard batch processing example sql_statement.addBatch(); } //We are now ready to perform a bulk batch insert //our Excel has only 4 records, you should set this suitably int[] totalRecords = new int[4]; try { totalRecords = sql_statement.executeBatch(); } catch(BatchUpdateException e) { //you should handle exception for failed records here totalRecords = e.getUpdateCounts(); } System.out.println ("Total records inserted : " + totalRecords.length); /* Close input stream */ input_document.close(); /* Close prepared statement */ sql_statement.close(); /* COMMIT transaction */ // conn.commit(); /* Close connection */ conn.close(); } } 

这是输出:“插入的logging总数:4”

excel文件有4行和2列填充简单的文本。 我看着数据库,不幸的是没有任何input,当我做这个简单的插入工作,我想稍后修改它为更多的插入图像文件,文件path将被存储在xls文件,也是这个版本是我需要采用xls xlsx也是。 我会很高兴,如果你能帮我find我的代码中的错误,或给一个更好的xls和xlsx工作的例子。 我使用Apache POI。

您可以简单地这样做:假设文件位于C:\ filename.xlsx

 Connection con = //...Complete connection initialization PreparedStatement pre = con.prepareStatement("load data infile 'C:\\filename.xlsx' into table tablename"); pre.executeUpdate(); 

一旦避免了以下错误,这段代码就可以正常工作:1.确保文件位于目录的根目录下,而不是在另一个目录中(这可能会导致exception)2.确保引用单个path引用