这是一个教大家使用excel表格,批量将数据导入到数据库的一个教程
通过Javaweb项目 的servlet技术实现,教程详细简单,跟着做就不会报错!
1.下载依赖包:
tomcat-jdbc的jar包下载:文件上传批量导入数据库依赖包 - 万策云盘
commons-fileupload的jar包下载:文件上传批量导入数据库依赖包 - 万策云盘
commons-io的jar包下载:文件上传批量导入数据库依赖包 - 万策云盘
servlet-api的jar包下载:文件上传批量导入数据库依赖包 - 万策云盘
2.编写html前端页面:
<form action="<%=basePath%>ImportMsg" enctype="multipart/form-data" method="post">
批量导入: <input style="border:1px solid black;" type="file" name="excelfilename">
<input type="submit" value="数据入库"/>
</form>
3.编写工具实现类 DatabaseOperation.java:
package cn.itbaizhan.tyut.exam.common;
//
//Source code recreated from a .class file by IntelliJ IDEA
//(powered by Fernflower decompiler)
//
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseOperation {
static Connection conn = null;
static Statement stmt = null;
public DatabaseOperation() {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("连接数据库...");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/exam?useUnicode=true&characterEncoding=UTF-8&useSSL=true", "root", "mmmmmmm");
System.out.println("实例化Statement对象...");
stmt = conn.createStatement();
System.out.println("完成数据库连接...");
} catch (SQLException var2) {
var2.printStackTrace();
} catch (Exception var3) {
var3.printStackTrace();
}
}
public void finalize() throws SQLException {
if (stmt != null) {
stmt.close();
}
if (stmt != null) {
conn.close();
}
}
public ResultSet select_op(String sql) throws SQLException {
if (sql == null) {
return null;
} else {
ResultSet rs = stmt.executeQuery(sql);
return rs;
}
}
public ResultSet select_op(String sql, int page, int count) throws SQLException {
if (sql != null && page >= 0 && count > 0) {
sql = sql + " limit " + page * count + ',' + count;
ResultSet rs = stmt.executeQuery(sql);
return rs;
} else {
return null;
}
}
public int update_op(String sql) {
if (sql == null) {
return -1;
} else {
int result = -1;
try {
result = stmt.executeUpdate(sql);
} catch (Exception var4) {
var4.printStackTrace();
}
return result;
}
}
public int select_count(int num, String table) {
if (num > 0 && table != null) {
int result = -1;
try {
ResultSet rs = stmt.executeQuery("select * from " + table);
rs.last();
result = rs.getRow();
if (result % num == 0) {
result /= num;
} else {
result = result / num + 1;
}
} catch (Exception var5) {
var5.printStackTrace();
}
return result;
} else {
return -1;
}
}
}
4.编写servlet类 ImportMsg.java:
package cn.itbaizhan.tyut.exam.sys.servlets;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import cn.itbaizhan.tyut.exam.common.DatabaseOperation;;
/**
* Servlet implementation class ImportMsg
*/
@WebServlet("/ImportMsg")
public class ImportMsg extends HttpServlet {
private static final long serialVersionUID = 1L;
// JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/exam";
// 数据库的用户名与密码,需要根据自己的设置
static final String USER = "root";
static final String PASS = "mmmmmmm";//此处为自己数据库的密码
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
java.sql.Connection conn = null;
java.sql.Statement stmt = null;
try {
// 注册 JDBC 驱动器
Class.forName("com.mysql.jdbc.Driver");
// 打开一个连接
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行 SQL 查询
stmt = conn.createStatement();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
try {
List items = upload.parseRequest(request);
InputStream is = null;
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
is = item.getInputStream();
}
}
Workbook workbook = Workbook.getWorkbook(is);
Sheet sheet = workbook.getSheet(0);
// 行数111
int rows = sheet.getRows();
// 列数
int columns = sheet.getColumns();
PreparedStatement ps = conn
.prepareStatement("insert into subject(scontent,sa,sb,sc,sd,skey,sstate) values(?,?,?,?,?,?,?)");
for (int i = 0; i < rows; i++) {
if (i == 0) {// 第一行是属性,不读取
continue;
}
Cell ce0 = ((jxl.Sheet) sheet).getCell(0, i);
Cell ce1 = ((jxl.Sheet) sheet).getCell(1, i);
Cell ce2 = ((jxl.Sheet) sheet).getCell(2, i);
Cell ce3 = ((jxl.Sheet) sheet).getCell(3, i);
Cell ce4 = ((jxl.Sheet) sheet).getCell(4, i);
Cell ce5 = ((jxl.Sheet) sheet).getCell(5, i);
Cell ce6 = ((jxl.Sheet) sheet).getCell(6, i);
String c0 = ce0.getContents();
String c1 = ce1.getContents();
String c2 = ce2.getContents();
String c3 = ce3.getContents();
String c4 = ce4.getContents();
String c5 = ce5.getContents();
int c6 = Integer.parseInt(ce6.getContents());
ps.setString(1, c0);
ps.setString(2, c1);
ps.setString(3, c2);
ps.setString(4, c3);
ps.setString(5, c4);
ps.setString(6, c5);
ps.setInt(7, c6);
ps.execute();
}
ps.close();
conn.close();
response.setContentType("text/html;charset=utf-8");
//显示弹窗并且当关闭弹窗后跳到指定页面
response.getWriter().write("<script>alert('叮咚,批量导入成功!');");
response.getWriter().flush();
//response.sendRedirect(" .html");// 重定向到成功插入学生数据的页面
} catch (FileUploadException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
功能实现,编写excel表格上传测试即可: