JavaWeb專案excel檔案匯入
阿新 • • 發佈:2019-01-01
專案期間有Excel檔案匯入 今天來整理一下
1. 首先在web頁面新增一個button按鈕 “匯入Excel”
注意: input 的型別必須是file才可以 name=“fileData”的名字要和後臺的屬性一致
2. html頁面:
$(function() {
$("#inputExcel").change(function(){
initProvince();
// 獲得檔案
var file = $("#inputExcel").val();
// 擷取上傳的檔案字尾
var extension = file.substring(file.lastIndexOf("." ),file.length);
// 驗證上傳檔案字尾是否合法
var strRegex = "(.xls|.xlsx)$";
var re = new RegExp(strRegex);
var flag;
// 如果不合法,在頁面上顯示出相應的提示訊息
if (!re.test(extension.toLowerCase())) {
layer.msg('檔名不合法,請上傳Excel檔案!', {
icon : 2
});
return false;
}
if(extension == ".xls"){
flag = 0;
}
if(extension == ".xlsx"){
flag = 1;
}
var parms = new Object();
// Excel版本flag
parms["flag"] = flag;
//如果你用不到以下引數的話就可以不用寫
parms["provinceNames"] = JSON.stringify(provinceNames);
//parms["areaNames"] = JSON.stringify(areaNames);
var options = {
//這個url是後臺的介面網址
url: ctx+'/organ/inputExcel.do?t=' + getNowDate(),
type: "post",
data: parms,
dataType: "json",
success: function (result) {
var json = eval(result);
if (json[Cons.RESULT] == Cons.SUCCESS) {
layer.msg('匯入成功!', {
icon : 1
});
}else if(json[Cons.RESULT] == null){
layer.msg(json[Cons.RESULT_MSG], {
icon : 2
});
}else if(json[Cons.RESULT] == "codeDuplication"){
layer.msg(json[Cons.RESULT_MSG], {
icon : 2
});
}else if(json[Cons.RESULT] == "telError"){
layer.msg(json[Cons.RESULT_MSG], {
icon : 2
});
}else if(json[Cons.RESULT] == "provinceError"){
layer.msg(json[Cons.RESULT_MSG], {
icon : 2
});
}else {
layer.msg('匯入失敗!', {
icon : 2
});
}
setTimeout('window.location.reload()',2000);
}
};
$("#form1").ajaxSubmit(options);
});
});
3. controller: 用來讀取excel檔案將資料儲存到資料中
@SuppressWarnings({ "deprecation", "unchecked" })
@RequestMapping(value = "/inputExcel", method=RequestMethod.POST)
public void upload(@RequestParam(value="fileData", required=false) MultipartFile file ,
@RequestParam("flag")String flag,
HttpServletRequest request, HttpServletResponse response)throws Exception {
Map<String, Object> resMap = new HashMap<String, Object>();
// 檔案轉換成輸入流
FileInputStream fis=(FileInputStream) file.getInputStream();
String provinceNames = request.getParameter("provinceNames");
JSONArray provinceNamesJson=JSONArray.fromObject(provinceNames);
// 獲取系統當前服務id
ServiceAdapter adapter = ServiceAdapter.getInstance();
String serviceID = adapter.getServiceId();
DecimalFormat df = new DecimalFormat("#");
if("0".equals(flag)){
// 建立xls工作薄
HSSFWorkbook workbook = null;
try {
workbook = new HSSFWorkbook(fis);
} catch (IOException e1) {
e1.printStackTrace();
}
// 得到工作表
HSSFSheet sheet = workbook.getSheetAt(0);
// 對應Excel的行
HSSFRow row = null;
// 得到Excel的總行數
int totalRows = sheet.getLastRowNum();
for (int i = 1; i <= totalRows; i++) {
row = sheet.getRow(i);
//這個實體是你需要匯入的檔案的實體
SysOrgan organ =new SysOrgan();
// 有序號的行 這個是一定要加上的
if(row.getCell(0)!=null){
// 機構名稱
if(row.getCell(1)!=null){
String name = "";
if(row.getCell(1).getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
name= df.format(row.getCell(1).getNumericCellValue());
}else{
name = row.getCell(1).toString();
}
if("".equals(name)){
resMap.put(Constants.RESULT, "null");
resMap.put(Constants.RESULT_MSG, "第"+i+"行機構名稱不能為空!");
ServletCom com = new ServletCom(request, response);
com.renderText(JSONObject.fromObject(resMap).toString());
return;
}else{
organ.setName(name);
}
}else{
resMap.put(Constants.RESULT, "null");
resMap.put(Constants.RESULT_MSG, "第"+i+"行機構名稱不能為空!");
ServletCom com = new ServletCom(request, response);
com.renderText(JSONObject.fromObject(resMap).toString());
return;
}
// 簡稱
String simpleName = "";
if(row.getCell(2).getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
simpleName= df.format(row.getCell(2).getNumericCellValue());
}else{
simpleName = row.getCell(2).toString();
}
organ.setSimpleName(simpleName);
// 編碼
if(row.getCell(3)!=null){
String code = "";
if(row.getCell(3).getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
code= df.format(row.getCell(3).getNumericCellValue());
}else{
code = row.getCell(3).toString();
}
if("".equals(code)){
resMap.put(Constants.RESULT, "null");
resMap.put(Constants.RESULT_MSG, "第"+i+"行編碼不能為空!");
ServletCom com = new ServletCom(request, response);
com.renderText(JSONObject.fromObject(resMap).toString());
return;
}
int codeNum = organService.selectOragnByCode(code,"");
// 重複code
if(codeNum > 0){
resMap.put(Constants.RESULT, "codeDuplication");
resMap.put(Constants.RESULT_MSG, "第"+i+"行編碼已經存在!");
ServletCom com = new ServletCom(request, response);
com.renderText(JSONObject.fromObject(resMap).toString());
return;
}else{
organ.setCode(code);
}
}else{
resMap.put(Constants.RESULT, "null");
resMap.put(Constants.RESULT_MSG, "第"+i+"行編碼不能為空!");
ServletCom com = new ServletCom(request, response);
com.renderText(JSONObject.fromObject(resMap).toString());
return;
}
// 地址
String adress = "";
if(row.getCell(4).getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
adress= df.format(row.getCell(4).getNumericCellValue());
}else{
adress = row.getCell(4).toString();
}
organ.setAdress(adress);
// 郵編
String zipCode = "";
if(row.getCell(5).getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
zipCode= df.format(row.getCell(5).getNumericCellValue());
}else{
zipCode = row.getCell(5).toString();
}
organ.setZipCode(zipCode);
// 負責人
String master = "";
if(row.getCell(6).getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
master= df.format(row.getCell(6).getNumericCellValue());
}else{
master = row.getCell(6).toString();
}
organ.setMaster(master);
// 電話
String tel = "";
if(row.getCell(7).getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
tel= df.format(row.getCell(7).getNumericCellValue());
}else{
tel = row.getCell(7).toString();
}
String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(tel);
if(m.matches()){
organ.setTel(tel);
}else{
resMap.put(Constants.RESULT, "telError");
resMap.put(Constants.RESULT_MSG, "第"+i+"行電話格式不正確!");
ServletCom com = new ServletCom(request, response);
com.renderText(JSONObject.fromObject(resMap).toString());
return;
}
// 傳真
String fax = "";
if(row.getCell(8).getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
fax= df.format(row.getCell(8).getNumericCellValue());
}else{
fax = row.getCell(8).toString();
}
organ.setFax(fax);
// 郵箱
String email = "";
if(row.getCell(9).getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
email= df.format(row.getCell(9).getNumericCellValue());
}else{
email = row.getCell(9).toString();
}
organ.setEmail(email);
// 預約flag可預約
organ.setOrderFlag(1);
// 儲存資料
organ = organService.save(organ);
}
}
}else{
// 建立xlsx工作薄
XSSFWorkbook workbook = null;
try {
workbook = new XSSFWorkbook(fis);
} catch (IOException e1) {
e1.printStackTrace();
}
// 得到工作表
XSSFSheet sheet = workbook.getSheetAt(0);
// 對應Excel的行
XSSFRow row = null;
// 得到Excel的總行數
int totalRows = sheet.getLastRowNum();
for (int i = 1; i <= totalRows; i++) {
row = sheet.getRow(i);
SysOrgan organ =new SysOrgan();
// 有序號的行
if(row.getCell(0)!=null){
// 機構名稱
if(row.getCell(1)!=null){
String name = "";
if(row.getCell(1).getCellType() == XSSFCell.CELL_TYPE_NUMERIC){
name= df.format(row.getCell(1).getNumericCellValue());
}else{
name = row.getCell(1).toString();
}
if("".equals(name)){
resMap.put(Constants.RESULT, "null");
resMap.put(Constants.RESULT_MSG, "第"+i+"行機構名稱不能為空!");
ServletCom com = new ServletCom(request, response);
com.renderText(JSONObject.fromObject(resMap).toString());
return;
}else{
organ.setName(name);
}
}else{
resMap.put(Constants.RESULT, "null");
resMap.put(Constants.RESULT_MSG, "第"+i+"行機構名稱不能為空!");
ServletCom com = new ServletCom(request, response);
com.renderText(JSONObject.fromObject(resMap).toString());
return;
}
// 簡稱
String simpleName = "";
if(row.getCell(2).getCellType() == XSSFCell.CELL_TYPE_NUMERIC){
simpleName= df.format(row.getCell(2).getNumericCellValue());
}else{
simpleName = row.getCell(2).toString();
}
organ.setSimpleName(simpleName);
// 編碼
if(row.getCell(3)!=null){
String code = "";
if(row.getCell(3).getCellType() == XSSFCell.CELL_TYPE_NUMERIC){
code= df.format(row.getCell(3).getNumericCellValue());
}else{
code = row.getCell(3).toString();
}
if("".equals(code)){
resMap.put(Constants.RESULT, "null");
resMap.put(Constants.RESULT_MSG, "第"+i+"行編碼不能為空!");
ServletCom com = new ServletCom(request, response);
com.renderText(JSONObject.fromObject(resMap).toString());
return;
}
int codeNum = organService.selectOragnByCode(code,"");
// 重複code
if(codeNum > 0){
resMap.put(Constants.RESULT, "codeDuplication");
resMap.put(Constants.RESULT_MSG, "第"+i+"行編碼已經存在!");
ServletCom com = new ServletCom(request, response);
com.renderText(JSONObject.fromObject(resMap).toString());
return;
}else{
organ.setCode(code);
}
}else{
resMap.put(Constants.RESULT, "null");
resMap.put(Constants.RESULT_MSG, "第"+i+"行編碼不能為空!");
ServletCom com = new ServletCom(request, response);
com.renderText(JSONObject.fromObject(resMap).toString());
return;
}
// 地址
String adress = "";
if(row.getCell(4).getCellType() == XSSFCell.CELL_TYPE_NUMERIC){
adress= df.format(row.getCell(4).getNumericCellValue());
}else{
adress = row.getCell(4).toString();
}
organ.setAdress(adress);
// 郵編
String zipCode = "";
if(row.getCell(5).getCellType() == XSSFCell.CELL_TYPE_NUMERIC){
zipCode= df.format(row.getCell(5).getNumericCellValue());
}else{
zipCode = row.getCell(5).toString();
}
organ.setZipCode(zipCode);
// 負責人
String master = "";
if(row.getCell(6).getCellType() == XSSFCell.CELL_TYPE_NUMERIC){
master= df.format(row.getCell(6).getNumericCellValue());
}else{
master = row.getCell(6).toString();
}
organ.setMaster(master);
// 電話
String tel="";
if(row.getCell(7).getCellType() == XSSFCell.CELL_TYPE_NUMERIC){
tel= df.format(row.getCell(7).getNumericCellValue());
}else{
tel = row.getCell(7).toString();
}
String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(tel);
if(m.matches()){
organ.setTel(tel);
}else{
resMap.put(Constants.RESULT, "telError");
resMap.put(Constants.RESULT_MSG, "第"+i+"行電話格式不正確!");
ServletCom com = new ServletCom(request, response);
com.renderText(JSONObject.fromObject(resMap).toString());
return;
}
// 傳真
String fax = "";
if(row.getCell(8).getCellType() == XSSFCell.CELL_TYPE_NUMERIC){
fax= df.format(row.getCell(8).getNumericCellValue());
}else{
fax = row.getCell(8).toString();
}
organ.setFax(fax);
// 郵箱
String email = "";
if(row.getCell(9).getCellType() == XSSFCell.CELL_TYPE_NUMERIC){
email= df.format(row.getCell(9).getNumericCellValue());
}else{
email = row.getCell(9).toString();
}
organ.setEmail(email);
// 預約flag可預約
organ.setOrderFlag(1);
// 儲存資料
organ = organService.save(organ);
}
}
}
// 返回結果
resMap.put(Constants.RESULT, Constants.SUCCESS);
ServletCom com = new ServletCom(request, response);
com.renderText(JSONObject.fromObject(resMap).toString());
}
4. mapper.xml檔案進行寫入儲存資料的sql
實體類中的屬性:
sql :
☺☺☺這樣一個excel的匯入就完成了, 如果有不足之處,歡迎指教☺☺☺