Import the excel file to insert the data into the database and display it in the form of a list

1、前端页面(只展示核心代码片段,即文件导入按钮)
<form class="form-inline" id="productSearchForm">
  <div class="form-group">
     <label for="productName">产品名称:</label>
                 <input type="text" class="form-control input-sm" name="productName" />
  </div>
  <button type="button" class="b-redBtn btn-i" id="searchBtn">
     <i class="iconfont"></i>查询
  </button>
  <button type="button" class="b-redBtn  btn-i" id="resetBtn">
     <i class="iconfont"></i>重置查询
  </button>
  <button type="button" class="b-redBtn  btn-i" id="addProductBtn">
     <i class="iconfont"></i>新增产品
  </button>
  <a id="downloadFile" href="<%=webpath%>/resources/js/orderCenter/productTabTemplet.xlsx">
    <button type="button" class="b-redBtn  btn-i" id="downloadTempletBtn">
      <i class="iconfont"></i>模板下载
    </button>
  </a>
  <input type="file" name="files" id="files" style="display:none;" />
   <button type="button" class="b-redBtn  btn-i" id="excelImportBtn" onclick="scan()">
      <i class="iconfont"></i>excel导入
   </button>
   <span id="fileInput"></span>    files.setAttribute("onchange", "fileCheck(this)");    var files = document.getElementById("files"); function scan() { 2. The core js code snippet shows
</form>




   layer.confirm('Before importing into excel, please download the template on the left, specify the format according to the template, complete the filling and import, otherwise the import will fail!', {
   icon: 3,
   btn: ['Yes','No'] / /button
   },function(index, layero){
layer.close(index);
files.click();
    });
}

function fileCheck(obj){
   for (var i = 0; i < obj.files.length; i++ ) {
var fileName = obj.files[i].name;
var postfix = obj.files[i].name.match(/^(.*)(\.)(.{1,8})$/)[ 3].toLowerCase(); //The regular expression to get the suffix name of the uploaded file;
var fileMaxSize=(obj.files[i].size/1024/1024).toFixed(2); //The front end gets the file to be uploaded file size
if (!(postfix == "xlsx" || postfix == "xls")) {
layer.confirm('The file type is incorrect, please re-upload the excel file!', {
        icon: 3,
        btn: ['Yes','No'] //Button
},function(index, layero){
      layer.close(index); //window.location.href=webpath+"/orderCenter/productManage
   ";
  });
$('#files').val('');
return false;
};

if(fileMaxSize > 1){
     layer.confirm('Excel file size cannot exceed 1M, please upload again!', {
     icon: 3,
     btn: ['Yes','No'] //Button
   } ,function(index, layero){
layer.close(index);
  });
  $('#files').val('');
return false;
}
   var fileNameInput=document.getElementById("fileInput");
   fileNameInput. innerText=fileName;
   //layer.msg(content, options, end) start importing data

   layer. msg('Start importing excel data, please wait...', {
     icon: 6,
     time: 3000 //3秒关闭(如果不配置,默认是3秒)
    }, function(){
//layer.alert('测试');
$.ajaxFileUpload({
url :webpath+"/orderCenter/importExcel",
fileElementId : "files",
type : "post",
dataType : "text",
data : {"flag":"开始导入"},
success : function(data){ 
        var result = data.replace("<pre>", "").replace("</pre>", "").replace("<PRE>", "").replace("</PRE>", "").replace(/<[^>]+>/g, "");
var resultFlag=$.parseJSON(result);    
receiveData(resultFlag); function receiveData(resultFlag){ }); console.log("Data has been imported into excel"); });
   }





    if(resultFlag.idIsNull=="true"){       
alert('Import failed, there is a null value in the imported product ID, located in the table '+resultFlag.errorLine+' row');
}
    if(resultFlag.idIsRepeat=="true" ){
    alert('Import failed, the imported product ID is duplicated, please check carefully!');
    }
    if(resultFlag.idCodeIsNotSame=="true"){
    alert('Import failed, the imported product ID is inconsistent with the product code, Located in the table '+resultFlag.errorLine+' row');
    }
    if(resultFlag.excelAndTabRepeat=="true"){
    alert('Import failed, the imported product code already exists in the database code table, the repeated product code is' +resultFlag.repeatCode);
    }
window.location.href=webpath+"/orderCenter/productManage";
console.log("Import complete");
}
    }
}
java core code display
// import product form data
@ResponseBody
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Map<String,Object> importExcel(String flag, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("text/html;charset=UTF-8");
String fileName = null;
if (request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
Iterator<?> iter = mr.getFileMap().values().iterator();
// 支持多文件上传,暂时是单文件的上传
if (iter.hasNext()) {
MultipartFile file = (MultipartFile) iter.next();
try {
Workbook book = null;
try {
book = new XSSFWorkbook(file.getInputStream());
} catch (Exception ex) {
book = new HSSFWorkbook(file.getInputStream());
}
// get the first workbook
Sheet sheet = book.getSheetAt(0);
Row row = null;
Row row2 = null;
Row row3 =null;
boolean idIsNull=false;
int errorLine=0;
//Determine whether product_id is repeated
boolean isRepeat = false;
//Whether the id and code are the same idCodeIsSame
boolean idCodeIsNotSame=false;
//Get the total number of rows
int totalRows = sheet.getLastRowNum( );
// get the total number of columns
int coloumNum = sheet.getRow(1).getPhysicalNumberOfCells();
System.out.println("total number of rows totalRows==>" + totalRows);
System.out.println("total number of columns coloumNum==>" + coloumNum);
System.out.println("Start getting the data in the table");
// The number of rows of table data is
int verifyNum = totalRows - 2;
String[] procIdArr = new String[verifyNum];
String[] procCodeArr = new String[ verifyNum];

for (int i = 3; i <= totalRows; i++) {
row2 = sheet.getRow(i);
if(null !=row2.getCell(0)){
System.out.println("row2.getCell (0)===>"+row2.getCell(0));
String tem = row2.getCell(0).toString();
System.out.println("The first column procId: starting from the third row -- "" + tem);
procIdArr[i - 3] = tem;
}
if(null==row2.getCell(0)){
idIsNull=true;
errorLine=i+1;
String errorLineStr=String.valueOf(errorLine);
params .put("idIsNull", "true" );
params.put("errorLine", errorLineStr);
System.out.println("--idIsNull---"+idIsNull+"---errorLine-->"+errorLine);
return params;
}
}

Set<String> set = new HashSet<String>();
for (String str : procIdArr) {
set.add(str);
}
if (set.size() != procIdArr.length) {
isRepeat = true;// 重复
params.put("idIsRepeat", "true");
return params;
} else {
isRepeat = false;// 不重复
}
System.out.println("判断productId是否存在重复的判断结果为==>"+isRepeat);

for (int i = 3; i <= totalRows; i++) {
row3 = sheet.getRow(i);
String tem3 = row3.getCell(1).toString();
System.out.println("The second column: starting from the third row --" + tem3);
procCodeArr[i - 3] = tem3;
}
for (int k = 0; k < procIdArr.length; k++) {
if(!procCodeArr[k].equals(procIdArr[k])){
idCodeIsNotSame=true;
errorLine=k+4;
String errorLineStr=String.valueOf(errorLine);
params.put("idCodeIsNotSame", "true");
params.put("errorLine", errorLineStr);
return params;
}
}
System.out.println("Whether the id and code are the same or not "+idCodeIsNotSame+" is the line ==>"+errorLine);

//check the form Whether the id is the same as the id in the database code table, if they are the same, do not allow it to be imported;
for(int i=0;i<procCodeArr.length;i++){
String excelAndTabRepeat=orderCenterService. validateProCodeIsExist(procCodeArr[i]);
if(null!=excelAndTabRepeat){
params.put("excelAndTabRepeat", "true");
params.put("repeatCode", excelAndTabRepeat);
return params;
}
}

for (int i = 3; i <= totalRows; i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
}
for (int k = 0; k < coloumNum; k++) {
String productField = sheet.getRow(2).getCell(k).toString().trim();
if (!"ORD".equalsIgnoreCase(productField) && !"RST6".equalsIgnoreCase(productField) && !"RST7".equalsIgnoreCase(productField)) {
if (row.getCell(k) == null) {
params.put(productField, "");
continue;
}
String productFieldValue = row.getCell(k).toString().trim();
params.put(productField, productFieldValue);
}
if ("ORD".equalsIgnoreCase(productField)) {
if (row.getCell(k) == null) {
params.put(productField, "");
continue;
}
String productFieldValue = row.getCell(k).toString().trim();
// 数据库码表中,字段类型为mediumint
params.put(productField, Integer.parseInt(productFieldValue));
}
if ("RST6".equalsIgnoreCase(productField) || "RST7".equalsIgnoreCase(productField)) {
if (row.getCell(k) == null) {
params.put(productField, "");
continue;
}
String productFieldValue = row.getCell(k).toString().trim();
// In the database code table, the field type is decimal
BigDecimal bd = new BigDecimal(productFieldValue);
params.put(productField, bd);
}
}
/ / Start executing test code
System.out.println("=======" + i);
System.out.println(params);
// Start importing table data into database
orderCenterService.importExcelDatas(params);
}
fileName = file.getOriginalFilename();
System.out.println("File name: " + fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
params.put("processNormal", "true");
return params;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326180872&siteId=291194637