2 otiankonglan123 oTianKongLan123 于 2016.05.12 14:47 提问

java的excel表格上传实现导入mysql数据库功能

在网页上有个按钮要实现点击按钮选择文件实现将文件导入mysql数据库的功能,上百度不知道应该用什么关键词搜索,求技术大牛给个网址

2个回答

oyljerry
oyljerry   Ds   Rxr 2016.05.12 15:13
已采纳

参考一下

 import java.io.FileInputStream;<br>
import java.io.IOException;<br>
import java.sql.Connection;<br>
import java.sql.DriverManager;<br>
import java.sql.PreparedStatement;<br>
import org.apache.poi.poifs.filesystem.POIFSFileSystem;<br>
//import org.apache.poi.ss.usermodel.Row;<br>
import org.apache.poi.ss.usermodel.*;<br><br>

public class TestApp {

    public static void main(String[] args) throws Exception {

        try {

            Class forName = Class.forName("com.mysql.jdbc.Driver");
            Connection con = null;
            con = DriverManager.getConnection("jdbc:mysql://localhost/tables", "root", "root");
            con.setAutoCommit(false);
            PreparedStatement pstm = null;
            FileInputStream input = new FileInputStream("C:\\Users\\Desktop\\a1.xls");
            POIFSFileSystem fs = new POIFSFileSystem(input);
            Workbook workbook;
            workbook = WorkbookFactory.create(fs);
            Sheet sheet = workbook.getSheetAt(0);
            Row row;
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                row = (Row) sheet.getRow(i);
                String name = row.getCell(0).getStringCellValue();
                String add = row.getCell(1).getStringCellValue();

                int  contact = (int) row.getCell(2).getNumericCellValue();

                String email = row.getCell(3).getStringCellValue();

                String sql = "INSERT INTO employee (name, address, contactNo, email) VALUES('" + name + "','" + add + "'," + contact + ",'" + email + "')";
                pstm = (PreparedStatement) con.prepareStatement(sql);
                pstm.execute();
                System.out.println("Import rows " + i);
            }
            con.commit();
            pstm.close();
            con.close();
            input.close();
            System.out.println("Success import excel to mysql table");
        } catch (IOException e) {
        }
    }

}
u014792378
u014792378   2016.05.12 15:06

用poi解析excel 然后入库

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!