本文中的方法只適合Excel2003,要讀取Excel2007最好使用poi.jar,據說poi.jar還在更新,jxl.jar已經不更新了,處理Excel文件的讀寫問題最好還是學習poi.jar ,后續會寫隨筆記錄poi.jar的用法。
讀取Excel文件中的內容可以用jxl.jar、poi.jar包,這里只介紹用jxl.jar包的實現方法。首先要導入jxl.jar包,例子中使用的框架是MyBatis+Spring MVC
思路:為避免向本地上傳病毒文件等安全問題,導入文件功能一般不會允許讀到文件在本地的路徑,因此要讀取本地文件中的內容必須先將文件上傳到服務器,然后從服務器的路徑中讀取。因此導入Excel文件數據的過程為:
(1)上傳Excel文件到服務器。
(2)用jxl.jar包中的方法讀取保存在服務器路徑中的Excel文件的數據。
(3)將讀取的數據保存到對象中並插入數據庫。
步驟1:文件上傳:
(1)jsp頁面的form表單中添加屬性:enctype="multipart/form-data"。
<form:form id="" modelAttribute="" action="" method="post" enctype="multipart/form-data" class="">
(2)form表單中有一個file組件 :
<input type="file" id="" name="" />
如果希望點擊“文件導入 ”按鈕就直接彈出選擇文件窗口,不想將文件的input顯示出來,可以將input設置成隱藏的,當點擊按鈕時觸發function,在觸發的function中設置該文件input的click事件。比如:
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<script type="text/javascript">
$(document).ready(function() {
//數據導入
$("#import").click(function(){
$("#excelFile").click();
});
});
</script>
</head>
<body>
<form:form id="uploadForm" modelAttribute="" action="" method="post" enctype="multipart/form-data" class="">
<input type="file" id="excelFile" name="" style="display:none"/>
<button id="import" class="" type="button"> Excel文件導入 </button>
</form:form>
</body>
</html>
如果需要對導入文件的格式進行驗證,可以寫在按鈕的onclick事件里:
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<script type="text/javascript">
$(document).ready(function() {
$("#import").click(function(){
$("#excelFile").click();
checkFile();
});
});
//檢查文件類型
function checkFile(){
var array = new Array('xls','xlsx');
var filename = $("#uploadfile ").val();
if(filename == ""){
alert("請選擇要上傳的文件");
return false;
}else {
//javaScript的match()方法檢索與正則表達式相同格式的字符串,返回一個數組,該數組的第0個元素返回的是匹配文本,其余的元素存放的是與正則表達式的子表達式匹配的文本。獲得文件類型除了下面的寫法外,還可以用:var extStart=filepath.lastIndexOf(".");fileType = filename.substring(extStart, filename.length);來替代
var fileType = filename.match( /^(.*)(\.)(.{1,8})$/)[3];//找到文件的后綴
var isExist = false;
for(i in array){
if(fileType.toLowerCase() == array[i].toLowerCase()){
isExist = true;
return true;
}
}
if(isExist == false ){
alert("文件類型不正確");
return false;
}
return true;
}
}
</script>
</head>
<body>
<form:form id="uploadForm " modelAttribute="" action="" method="post" enctype="multipart/form-data" class="">
<input type="file" id="excelFile" name="" style="display:none"/>
<button id="import" class="" type="button"> Excel文件導入 </button>
</form:form>
</body>
</html>
(3)選擇完文件且驗證過文件類型后,提交表單跳轉到導入文件對應的處理方法
<head>
<script type="text/javascript">
$(document).ready(function() {
//數據導入
$("#import").click(function(){
$("#excelFile").click();
var t = checkFile();
if(t){
$("#uploadForm").attr("action","${ctx}/app/test/importExcel");
$("#uploadForm").submit();
}
});
});
</script>
</head>
(4)后台類
//Excel格式數據導入
@RequestMapping(value = "importExcel")
public String importExcel(@RequestParam(value="excelFile", required=false) MultipartFile file, RedirectAttributes redirectAttributes, HttpServletResponse response)
{
InputStream fis = null;
String uploadPath = SystemPath.getSysPath() + "WEB-INF/views/app/upload" + File.separator;
String fileName = file.getOriginalFilename(); //文件名稱
String path = uploadPath + fileName.substring(0, fileName.lastIndexOf(".")) + DateTimeUtil.get_YYYYMMDDHHMMSS(ne Date())+fileName.substring(fileName.lastIndexOf("."), fileName.length());//為了在服務器中放的文件不重復,修改文件名,在文件名中加上時間
File uploadFile = new File(path);
try {
file.transferTo(uploadFile);//將本地文件中的內容上傳到服務器文件
fis = new FileInputStream(path);
Workbook wb = Workbook.getWorkbook(fis);//jxl.jar中讀取Excel文件內容的方法
if(!judgeExcelModel(wb)){//judgeExcelModel為判斷Excel文件格式的方法,根據具體情況自行添加
FileUtils.deleteFile(path);
addMessage(redirectAttributes, "Excel格式錯誤,請下載平台提供的模板");
}else{
int sheet_size = wb.getNumberOfSheets();//工作欄的數量
for(int index=0;index<sheet_size;index++){
Sheet sheet = wb.getSheet(index);//工作欄的內容
for(int i=1;i<sheet.getRows();i++){
Student stu = new Student();
String age = sheet.getCell(0, i).getContents();
String name = sheet.getCell(1, i).getContents();
String class = sheet.getCell(2, i).getContents();
String school = sheet.getCell(3, i).getContents();
stu .setAge(age );
stu .setName(name);
stu .setClass(class);
stu .setSchool(school);
stu Service.insert(stu );
}
}
addMessage(redirectAttributes, "批量導入數據成功");
FileUtils.deleteFile(path);//導入成功后將服務器中的文件刪掉
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally{
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
到這里,已經完成導入Excel文件數據的功能,在具體應用時,應該還需要對插入數據庫的各數據進行驗證,將驗證通過的記錄放在list集合中,等所有記錄驗證結束后再一起將驗證通過的數據插入到數據庫。