Java excel表上传到mysql表

时间:2018-01-14 15:37:04

标签: java mysql excel

在我的应用程序中,我需要上传excel表并将这些数据输入我的计算中。所以我使用这个java代码来做上传功能

try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/smartmenu","root","");
        con.setAutoCommit(false);
        PreparedStatement pstm = null ;
        FileInputStream input = new FileInputStream("C://Users/Dhananjana/Desktop/tes/test.xls");
        POIFSFileSystem fs = new POIFSFileSystem( input );
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);
        Row row;
        for(int i=1; i<=sheet.getLastRowNum(); i++){
            row = (Row)sheet.getRow(i);
            int id = (int) row.getCell(0).getNumericCellValue();
            String name = row.getCell(1).getStringCellValue();
            String address = row.getCell(2).getStringCellValue();
            String sql = "INSERT INTO test VALUES('"+id+"','"+name+"','"+address+"')";
            pstm = (PreparedStatement) con.prepareStatement(sql);
            pstm.execute();
            System.out.println("Import rows "+i);
        }
        con.commit();
        pstm.close();

虽然我正在尝试此代码,但我收到以下错误。

  

线程中的异常&#34; main&#34; java.lang.ClassCastException:org.apache.poi.hssf.usermodel.HSSFRow无法强制转换为org.apache.poi.ss.usermodel.Row       at employee.payroll.system.ImportData.main(ImportData.java:33)   :::第33行:::: row =(行)sheet.getRow(i);

如何解决此错误

1 个答案:

答案 0 :(得分:0)

Row row;更改为HSSFRow row;。如果需要,请在文件开头添加import org.apache.poi.hssf.usermodel.HSSFRow;