如何将excel中的行插入mysql db?

时间:2015-02-04 14:50:40

标签: java mysql excel jdbc apache-poi

我用google搜索并用Google搜索但找不到合适的工作示例,最后我将this转换为mysql import for my case,这是代码:

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

这是输出: &#34;插入的总记录数:4&#34;

excel文件有4行2列,内容是简单文本。我看看数据库很遗憾没有导入任何内容,当我使这个简单的插入工作时我想稍后修改它以获得更多的插入图像文件,文件路径将存储在xls文件中,此版本也适用于xls我需要采用 xlsx 也是。如果你能帮助我在代码中找到错误或为xls和xlsx提供更好的工作示例,我将很高兴。我正在使用Apache POI。

1 个答案:

答案 0 :(得分:1)

你可以这样做: 假设文件位于C:\ filename.xlsx

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

一旦避免以下错误,此代码将完美运行: 1.确保文件位于目录的根目录而不是另一个目录(可能导致异常) 2.确保使用单引号引用路径