最近要做一個excel表添加數據到數據庫。網上找了很多,有些雜,但我總結了一下,再次提供給需要的人。
首先需要導入jxl包,如果你是maven項目直接去依賴地址搜查複製,如果是普通的導包項目你從查詢到的結果頁面下載即可
下一步,前端頁面上傳代碼
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Insert title here</title>
<style>
.upload-ex{
margin: 0 20px;
}
#uploadEventBtn, .btn-upload{
height: 36px;
width: 100px;
border-radius: 4px;
border: none;
cursor: pointer;
outline: none;
}
.btn-upload:hover{
background: #cccccc;
color: white;
}
#uploadEventBtn:hover{
background: #cccccc;
color: white;
}
#uploadEventPath{
border: 1px solid #cccccc;
border-radius: 4px;
height: 36px;
width: 200px;
text-indent: 10px;
}
</style>
</head>
<body>
<form class="upload-ex">
<input id="uploadEventPath" disabled="disabled" type="text" placeholder="請選擇excel表" />
<button id="uploadEventBtn" type="button">選擇文件</button>
<input id="uploadEventFile" type="file" name="file" style="display: none;;" >
<button type="button" class="btn btn-success btn-sm btn-upload" οnclick="user.uploadBtn()">上傳</button>
</form>
<!-- <script src="../js/jquery-3.2.1.min.js"></script> -->
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script type="text/javascript">
var user;
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 = '/TecZH/importExcel';//自己的controller路徑 這裏可能會報404 注意f12查看
var formData = new FormData($('form')[0]);
user.sendAjaxRequest(url, 'POST', formData);
}
};
this.sendAjaxRequest = function (url, type, data) {
$.ajax({
url: url,
type: type,
data: data,
success: function (result) {
alert(result);
},
error: function () {
alert("excel上傳失敗");
},
cache: false,
contentType: false,
processData: false
});
};
}
$(function () {
user = new User();
user.init();
});
</script>
</body>
</html>
只是一個簡單的調用後臺接口,亦可以自己寫。下面貼出java代碼
package controller;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import model.User;
import service.UserService;
@Controller
public class UpLoadFileController {
@Autowired
private UserService userService;
//讀取excel文件並整理數據添加到數據庫
@RequestMapping("/importExcel")
@ResponseBody
public void import2(HttpServletRequest request)
throws IOException, BiffException {//這裏也可以直接接收MultipartFile file
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
MultipartFile file = files.get(0);
// 導入已存在的Excel文件,獲得只讀的工作薄對象
FileInputStream fis = (FileInputStream)file.getInputStream();//FileInputStream讀取springMVc使用的的MultipartFile文件
//FileInputStream fis = new FileInputStream("D:/study/123.xls");讀取已存在excel表
Workbook wk = Workbook.getWorkbook(fis);
// 獲取第一張Sheet表
Sheet sheet = wk.getSheet(0);
// 獲取總行數
int rowNum = sheet.getRows();
System.out.println("插入總行數:"+rowNum);
User u =null;
// 從數據行開始迭代每一行
for (int i = 1; i < rowNum; i++) {//從第二行開始,並未判斷第一行標題列去判斷字段
//先判斷插入的數據是否和數據庫的數據重複
// if(userService.findUser(((jxl.Sheet) sheet).getCell(0, i).getContents())>0) {
// continue;
// }
u= new User();
// getCell(column,row),表示取得指定列指定行的單元格(Cell)
// getContents()獲取單元格的內容,返回字符串數據。適用於字符型數據的單元格
// 使用實體類封裝單元格數據
u.setUsername(sheet.getCell(0, i).getContents());
u.setPassword(sheet.getCell(1, i).getContents());
// double x = ((NumberCell)sheet.getCell(2, i)).getValue();
u.setAge(Integer.valueOf(sheet.getCell(2, i).getContents()));
u.setSex(Integer.valueOf(sheet.getCell(3, i).getContents()));
u.setMobile(sheet.getCell(4, i).getContents());
userService.saveUser(u);
// System.out.println("成功插入:"+sheet.getCell(0, i).getContents());
/*// 判斷單元格的類型,單元格主要類型LABEL、NUMBER、DATE
31 if (sheet.getCell(2, i).getType == CellType.NUMBER) {
32
33 // 轉化爲數值型單元格
34 NumberCell numCell = (NumberCell) sheet.getCell(2, i);
35 // NumberCell的getValue()方法取得單元格的數值型數據
36 info.setRscore(numCell.getValue());
37
38 }
39 if (sheet.getCell(3, i).getType == CellType.NUMBER) {
40 NumberCell numCell = (NumberCell) sheet.getCell(3, i);
41 info.setRscore(numCell.getValue);
42 }
43
44 if (sheet.getCell(4, i).getType == CellType.DATE) {
45 DateCell dateCell = (DateCell) sheet.getCell(4, i);
46 // DateCell的getDate()方法取得單元格的日期型數據
47 info.setDate(dateCell.getDate());
48 }*/
}
fis.close();
wk.close();
}
}
至於其中的添加操作,就是你後臺數據添加的接口,具體事宜已經在代碼的註釋裏了。下面準備一張excel測試一下
至此已將數據寫入數據庫。