一、電商系統和辦公系統時常會用到Excel的導入與導出,在JAVA代碼實現時,通常使用POI來處理,今天用一個demo爲大家介紹POI上傳excel文件並將數據導入數據庫的實現過程。demo是一個jsp/servlet+maven的web項目。
二、環境:
數據庫:mysql
excel:*.xls
工具:IDEA
三、介紹MAVEN配置文件,引入poi,jstl(因爲頁面展示用到了el表達式),mysql
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency><groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.5-FINAL</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
前端頁面:
前端代碼:
<%@ 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<String> array = new ArrayList<String>();
for(int m=0;m<arr.length;m++){
if(arr[m].getName().endsWith(".xls")) {
array.add(arr[m].getName());
}
}
System.out.println(array.size());
%>
<html>
<body>
<h2>Hello World!</h2>
<meta charset="utf-8">
<h3>上傳</h3>
<form action="UploadServlet" enctype="multipart/form-data" method="post">
<input type="file" id="excel" name="excel" />
<input type="submit" value="Upload">
</form>
<hr>
<h3>下載目錄</h3>
<ul>
<%--這裏是下載操作--%>
<c:forEach var="i" items="<%=array%>">
<a href="DownloadServlet?filename=${i}"><li>${i}</li></a>
</c:forEach>
</ul>
</body>
</html>
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<params.length;i++){
ps.setObject(i+1, params[i]);
}
updateRows = ps.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}
return updateRows;
}
//查詢
public ResultSet executeSQL(String sql,Object[] params){
getConnection();
try{
ps = conn.prepareStatement(sql);
for(int i=0;i<params.length;i++){
ps.setObject(i+1, params[i]);
}
rs = ps.executeQuery();
}catch(SQLException e){
e.printStackTrace();
}
return rs;
}
//關閉資源
public boolean close(){
if(rs!=null){
try{
rs.close();
}catch(SQLException E){
E.printStackTrace();
return false;
}
}
if(ps !=null){
try{
ps.close();
}catch(SQLException E){
E.printStackTrace();
return false;
}
}
if(stmt!=null){
try{
stmt.close();
}catch(SQLException E){
E.printStackTrace();
return false;
}
}
if(conn!=null){
try{
conn.close();
}catch(SQLException E){
E.printStackTrace();
return false;
}
}
return true;
}
}
public class UserDao extends BaseDao{
//用於上傳excel時向數據庫添加用戶的方法
public int addAllUser(List<User> 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<User> getAllUser() throws SQLException {
List<User> users = new ArrayList<User>();
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<User> users = getUser(excelname); //讀取excel中的users,生成user_table.xls
int exi = userDao.addAllUser(users); //將讀取的List<User>插入數據庫
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.print("<script>添加成功,一共有:"+exi+"條數據</script>");
}
//傳入文件路徑讀取excel,得到List<User>
public List<User> 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<User> userList = new ArrayList<User>();
User user = null;
int i = 1; //控制讀取數
while (i<rowNum) {
user = new User();
i++;
user.setUid((int) (sheet.getRow(i).getCell(0).getNumericCellValue()));
user.setUsername(sheet.getRow(i).getCell(1).getStringCellValue());
user.setAge((int) (sheet.getRow(i).getCell(2).getNumericCellValue()));
user.setText(sheet.getRow(i).getCell(3).getStringCellValue());
userList.add(user);
}
return userList;
}
//將上傳的excel文件保存爲文件,可選進行備份操作。
public void getFile(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.getInputStream();
Part part = request.getPart("excel");
String cd = part.getHeader("Content-Disposition");
String[] cds = cd.split(";");
String filename = cds[2].split("=")[1].replace("\"","");
System.out.println("文件名:"+filename);
InputStream is = part.getInputStream();
filename = savePath+filename;
System.out.println("路徑:"+filename);
excelname = filename;
File file = new File(filename);
FileOutputStream fos = new FileOutputStream(file); //生成excel文件
byte[] b = new byte[1024];
int len = 0;
while((len = is.read(b)) != -1){
fos.write(b,0,len);
}
is.close();
fos.close();
}
}
六、結果演示
七、注意
(1)Excel上傳與下載時都容易出現的中文亂碼問題,應該注意幾點
jsp頁面顯示亂碼問題:
<%@page language="java" contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %>
<meta charset="utf-8">
servlet獲取後亂碼問題:
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