问题描述
- java的excel表格上传实现导入mysql数据库功能
-
在网页上有个按钮要实现点击按钮选择文件实现将文件导入mysql数据库的功能,上百度不知道应该用什么关键词搜索,求技术大牛给个网址
解决方案
参考一下
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) {
}
}
}
解决方案二:
用poi解析excel 然后入库
时间: 2024-10-30 01:49:39