1. 程式人生 > >Java匯入excel並儲存到資料庫

Java匯入excel並儲存到資料庫

首先建立好excel表格,並對應excel表格建立資料庫表。

前臺jsp頁面:其中包含js

複製程式碼
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
> <html> <head> <base href="<%=basePath%>"> <title>匯入excel</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta
http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="匯入excel"> <script type="text/javascript" src="view/js/jquery-1.8.2.js"></script> </head> <script type="text/javascript"> var User = function() { this.init
= function() { //模擬上傳excel $("#uploadEventBtn").unbind("click").bind("click", function() { $("#uploadEventFile").click(); }); $("#uploadEventFile").bind("change", function() { $("#uploadEventPath").attr("value", $("#uploadEventFile").val()); }); }; //點選上傳鈕 this.uploadBtn = function() { var uploadEventFile = $("#uploadEventFile").val(); if (uploadEventFile == '') { alert("請擇excel,再上傳"); } else if (uploadEventFile.lastIndexOf(".xls") < 0) {//可判斷以.xls和.xlsx結尾的excel alert("只能上傳Excel檔案"); } else { var url = "excel/import.do"; var formData = new FormData($('form')[0]); user.sendAjaxRequest(url, "POST", formData); } }; this.sendAjaxRequest = function(url, type, data) { $.ajax({ url : url, type : type, data : data, dataType : "json", success : function(result) { alert(result.message); }, error : function(result) { alert(result.message); }, cache : false, contentType : false, processData : false }); }; }; var user; $(function() { user = new User(); user.init(); }); </script> <body> <form enctype="multipart/form-data" id="batchUpload" action="/excel/import" method="post" class="form-horizontal"> <button class="btn btn-success btn-xs" id="uploadEventBtn" style="height:26px;" type="button" >擇檔案</button> <input type="file" name="file" style="width:0px;height:0px;" id="uploadEventFile"> <input id="uploadEventPath" disabled="disabled" type="text" placeholder="請擇excel表" style="border: 1px solid #e6e6e6; height: 26px;width: 200px;" /> </form> <button type="button" class="btn btn-success btn-sm" onclick="user.uploadBtn()" >上傳</button> </body> </html>
複製程式碼

後臺程式碼:自己修改的一些判斷條件

/**
* 儲存上傳的Excel檔案資料
*/
@PostMapping("/Excel")
// @RequiresPermissions("biz:userwebsite:save")
public R saveExcel(HttpServletRequest request) {
MultipartFile file = null;
Map<String, Object> map = new HashMap<String, Object>();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request,
MultipartHttpServletRequest.class);
file = multipartRequest.getFile("file");
} else {
map.put("message", "請選擇檔案");
return R.ok().put("map", map);
}
if (file != null) {
String result = tdeviceService.readExcelFile(file);
map.put("message", result);
}
return R.ok().put("map", map);
}

Controller

複製程式碼
 1 import java.util.HashMap;
 2 import java.util.Map;
 3 
 4 import javax.servlet.http.HttpServletRequest;
 5 import javax.servlet.http.HttpServletResponse;
 6 
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.stereotype.Controller;
 9 import org.springframework.web.bind.annotation.RequestMapping;
10 import org.springframework.web.bind.annotation.RequestMethod;
11 import org.springframework.web.bind.annotation.RequestParam;
12 import org.springframework.web.bind.annotation.ResponseBody;
13 import org.springframework.web.multipart.MultipartFile;
14 
15 import service.ImportService;
16 
17 @Controller
18 @RequestMapping("/excel")
19 public class ImportExcelController{
20     @Autowired(required=true)
21     private ImportService importService;
22     
23     //匯入excel
24     @RequestMapping(value = "/import", method=RequestMethod.POST)
25     @ResponseBody
26     public Map<String, Object> importExcel(@RequestParam(value="file",required = false) MultipartFile file, HttpServletRequest request,HttpServletResponse response){
27         Map<String, Object> map = new HashMap<String, Object>();
28         String result = importService.readExcelFile(file);  
29         map.put("message", result);
30         return map;  
31     }  
32 
33 }
複製程式碼

service:

複製程式碼
 1 import org.springframework.web.multipart.MultipartFile;
 2 
 3 public interface ImportService {  
 4       
 5     /** 
 6      * 讀取excel中的資料,生成list 
 7      */  
 8     String readExcelFile(MultipartFile file);  
 9   
10 } 
複製程式碼

serviceImpl:

String fileName = file.getOriginalFilename();// 獲取檔名
   
        //判斷檔案是否是excel檔案  
        if(!fileName.endsWith("xls") && !fileName.endsWith("xlsx")){  
        return result="請選擇Excel檔案";
        }  

 1 import java.util.List;
 2 import java.util.Map;
 3 
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.stereotype.Service;
 6 import org.springframework.web.multipart.MultipartFile;
 7 
 8 import service.ImportService;
 9 import controller.ReadExcel;
10 import dao.UserDao;
11 
12 @Service  
13 public class ImportServiceImpl implements ImportService {
14     @Autowired(required = true) 
15     private UserDao userDao;
16     @Override
17     public String readExcelFile(MultipartFile file) {
18         String result = "";  
19         //建立處理EXCEL的類  
20         ReadExcel readExcel = new ReadExcel();  
21         //解析excel,獲取上傳的事件單  
22         List<Map<String, Object>> userList = readExcel.getExcelInfo(file);  
23         //至此已經將excel中的資料轉換到list裡面了,接下來就可以操作list,可以進行儲存到資料庫,或者其他操作,  
24         for(Map<String, Object> user:userList){
25             int ret = userDao.insertUser(user.get("name").toString(), user.get("sex").toString(), Integer.parseInt(user.get("age").toString()));
26             if(ret == 0){
27                 result = "插入資料庫失敗";
28             }
29         }
30         if(userList != null