Java實現從網頁上傳匯入excel資料到資料庫
阿新 • • 發佈:2019-01-02
一晃已經是十月份的最後一天了,時間過得很快...
專案中通過excel往資料庫批量匯入的功能頗為常見,所以今天整理出來一份簡單的例子,為了以後方便使用,同時也為大家實現功能作為一個參考,該框架採用SSM,可以結合自身業務修改即可使用
Spring配置檔案載入解析器(檔案上傳)
<!-- 載入 multipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="307200000"/> <property name="maxInMemorySize" value="4096" /> </bean>
HTML介面
<form class="form form-horizontal" id="form-article-add" enctype="multipart/form-data"> <div class="row cl"> <label class="form-label col-xs-4 col-sm-2">檔案:</label> <div class="formControls col-xs-8 col-sm-9"> <span class="btn-upload form-group"> <input class="input-text upload-url" type="text" name="uploadfile" id="uploadfile" readonly nullmsg="請新增附件!" style="width:200px"> <a href="javascript:void();" class="btn btn-primary radius upload-btn"><i class="Hui-iconfont"></i> 瀏覽檔案</a> <input type="file" multiple name="file" class="input-file" id="file"> </span> </div> </div> <div class="row cl"> <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-2"> <button onClick="importUsers();" class="btn btn-primary radius" type="button"><i class="Hui-iconfont"></i> 匯入資料</button> <button onClick="cancel();" class="btn btn-default radius" type="button"> 取消 </button> </div> </div> </form>
的JavaScript的程式碼
/*匯入資料*/ function importUsers(){ //var clientid = $("#clientid").val(); var FormDatas=new FormData($("#form-article-add")[0]); var fileName=$("#file").val(); if(fileName == '') { layer.msg('請選擇檔案!',{ icon:MSG_CHECK, time:MSG_TIME }); return false; } //驗證檔案格式 var fileType = (fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length)).toLowerCase(); if (fileType != 'xlsx') { layer.msg('檔案格式不正確!',{ icon:MSG_CHECK, time:MSG_TIME }); return false; } $.ajax({ type:'post', url:'', async : false, cache : false, contentType : false, processData : false, data:FormDatas, success: function(data){ if(data == "error"){ layer.msg("檔案匯入失敗,請重新上傳!", { icon: OPER_SB, shade: [0.3, '#393D49'], // 透明度 顏色 time:5000 }); return false; }else{ layer.msg("檔案匯入成功!", { icon: OPER_CG, shade: [0.3, '#393D49'], // 透明度 顏色 time:5000 }); window.location.reload(); return false; } }, error : function(data){ console.log(data.msg); } }); }
sqlserver-表結構
控制器程式碼
/**
* 匯入學員清單
* @param file
* @param clientid
* @return
* @throws IOException
*/
@RequestMapping("importUsers")
@ResponseBody
public String importUsers(@RequestParam MultipartFile file,Integer clientid,HttpServletRequest request) throws IOException{
boolean FLAG;//身份狀態
List<Users> list = new ArrayList<Users>();
XSSFWorkbook workbook =null;
//把MultipartFile轉化為File
CommonsMultipartFile cmf= (CommonsMultipartFile)file;
DiskFileItem dfi=(DiskFileItem) cmf.getFileItem();
File fo=dfi.getStoreLocation();
//建立Excel,讀取檔案內容
workbook = new XSSFWorkbook(FileUtils.openInputStream(fo));
//獲取第一個工作表
XSSFSheet sheet = workbook.getSheet("學員資訊");
//獲取sheet中第一行行號
int firstRowNum = sheet.getFirstRowNum();
//獲取sheet中最後一行行號
int lastRowNum = sheet.getLastRowNum();
try {
//迴圈插入資料
for(int i=firstRowNum+1;i<=lastRowNum;i++){
XSSFRow row = sheet.getRow(i);
Users users = new Users();
users.setClientid(clientid);
users.setAdddate(date);
users.setStatus(true);//預設為啟用狀態
XSSFCell username = row.getCell(0);//學員名稱
if(username!=null){
username.setCellType(Cell.CELL_TYPE_STRING);
users.setUsername((username.getStringCellValue()));
}
XSSFCell phone = row.getCell(1);//聯絡方式
if(phone!=null){
phone.setCellType(Cell.CELL_TYPE_STRING);
users.setPhone((phone.getStringCellValue()));
}
XSSFCell post = row.getCell(2);//職位
if(post!=null){
post.setCellType(Cell.CELL_TYPE_STRING);
users.setPost((post.getStringCellValue()));
}
XSSFCell identitys = row.getCell(3);//身份
if(identitys!=null){
identitys.setCellType(Cell.CELL_TYPE_STRING);
if(identitys.getStringCellValue().equals("學員")){
FLAG = false;
}else{
FLAG = true;
}
users.setIdentitys(FLAG);
}
list.add(users);
}
//usersMapper.insert(list);//往資料庫插入資料
} catch (Exception e) {
e.printStackTrace();
} finally {
workbook.close();
}
}
Excel中中的模板
選擇的Excel檔案上傳,看資料是否匯入資料庫
通用的工具類 :