JAVA POI上傳excel檔案到資料庫並備份(上)
阿新 • • 發佈:2019-01-02
一、電商系統和辦公系統時常會用到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>
前端頁面:
前端程式碼:
Excel檔案:<%@ 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>
資料庫表結構:
五、程式碼實現
JDBC連線資料庫:
PropertiesUtils.java
BaseDao.javapublic 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;
}
}
UserDao.java
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;
}
}
config.properties
##jdbc config
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8
username = root
password = 123456
Upload.java(關鍵servlet)
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