一、电商系统和办公系统时常会用到Excel的导入与导出,在JAVA代码实现时,通常使用POI来处理,今天用一个demo为大家介绍POI上传excel文件并将数据导入数据库的实现过程。demo是一个jsp/servlet+maven的web项目。
二、环境:
数据库:mysql
excel:*.xls
工具:IDEA
三、介绍MAVEN配置文件,引入poi,jstl(因为页面展示用到了el表达式),mysql
junit
junit
3.8.1
test
org.apache.poi
poi-ooxml
3.5-FINAL
mysql
mysql-connector-java
5.1.32
javax.servlet
jstl
1.2
taglibs
standard
1.1.2
前端代码:
<%@ page import="java.io.File" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@page language="java" contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page isELIgnored="false" %>
<%--显示文件夹中已上传的文件--%>
<%
String savePath = getClass().getResource("/").getPath();
File file = new File(savePath);
File[] arr = file.listFiles();
List array = new ArrayList();
for(int m=0;m
Hello World!
上传
下载目录
<%--这里是下载操作--%>
- ${i}
Excel文件:
数据库表结构:
五、代码实现
JDBC连接数据库:
PropertiesUtils.java
public class PropertiesUtils {
static Properties prop = new Properties();
/**
* @param fileName 需要加载的properties文件,文件需要放在src根目录下
* 是否加载成功
*/
public static boolean loadFile(String fileName){
try {
prop.load(PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 根据KEY取回相应的value
*/
public static String getPropertyValue(String key){
return prop.getProperty(key);
}
}
public class BaseDao {
protected Connection conn;
protected PreparedStatement ps;
protected Statement stmt;
protected ResultSet rs;
//获取数据库连接
public boolean getConnection(){
//读取配置信息
PropertiesUtils.loadFile("config.properties");
String url = PropertiesUtils.getPropertyValue("url");
String username = PropertiesUtils.getPropertyValue("username");
String password = PropertiesUtils.getPropertyValue("password");
String driver = PropertiesUtils.getPropertyValue("driver");
//加载jdbc驱动
try{
Class.forName(driver);
//与数据库建立连接
conn = DriverManager.getConnection(url,username,password);
}catch(ClassNotFoundException e){
e.printStackTrace();
return false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
//增删改
public int executeUpdate(String sql,Object[] params){
int updateRows = 0;
getConnection();
try{
ps = conn.prepareStatement(sql);
for(int i= 0;i
public class UserDao extends BaseDao{
//用于上传excel时向数据库添加用户的方法
public int addAllUser(List users){
int n = 0;
for(User user:users){
try{
String sql = "insert into user_table values(?,?,?,?)";
Object[] params = {user.getUid(),user.getUsername(),user.getAge(),user.getText()};
int ex = this.executeUpdate(sql,params);
n+=ex;
}catch (Exception e){
e.printStackTrace();
}
}
return n;
}
//用于下载导出excel时用的数据库查询方法
public List getAllUser() throws SQLException {
List users = new ArrayList();
User user = null;
try{
String sql = "select * from user_table";
Object[] params = {};
ResultSet rs = this.executeSQL(sql,params);
while(rs.next()){
user = new User();
user.setUid(rs.getInt(0));
user.setUsername(rs.getString(1));
user.setAge(rs.getInt(2));
user.setText(rs.getString(3));
users.add(user);
}
}catch (SQLException e){
e.printStackTrace();
}
return users;
}
}
##jdbc config
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8
username = root
password = 123456
import Dao.UserDao;
import Entity.User;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* Created by qianbei476 on 2017/6/22.
*/
@MultipartConfig
@WebServlet(urlPatterns="/UploadServlet")
public class Upload extends HttpServlet {
private POIFSFileSystem fs;
private HSSFWorkbook wb;
private HSSFSheet sheet;
private HSSFRow row;
UserDao userDao = new UserDao();
public String savePath = getClass().getResource("/").getPath();
public static String excelname;
//上传文件保存目录
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
getFile(request, response); //上传文件
List users = getUser(excelname); //读取excel中的users,生成user_table.xls
int exi = userDao.addAllUser(users); //将读取的List插入数据库
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.print("");
}
//传入文件路径读取excel,得到List
public List getUser(String fileurl) throws IOException {
InputStream is = new FileInputStream(fileurl);
fs = new POIFSFileSystem(is);
wb = new HSSFWorkbook(fs);
sheet = wb.getSheetAt(0);
row = sheet.getRow(0);
int rowNum = sheet.getLastRowNum();
System.out.println("excel总行数:" + (rowNum+1));
System.out.println("标题为:" + row.getCell(0));
List userList = new ArrayList();
User user = null;
int i = 1; //控制读取数
while (i
六、结果演示
七、注意
(1)Excel上传与下载时都容易出现的中文乱码问题,应该注意几点
jsp页面显示乱码问题:
<%@page language="java" contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %>
request.setCharacterEncoding("utf-8");
servlet返回后乱码问题:
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setContentType("application/vnd.ms-excel;charset=gb2312");
数据库操作乱码问题:
url = jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8