- 需求:
首先点击“模板下载”下载excel模板(房号模板.xlsx直接存放在工程下),存放需要导入的数据==(导入一列数据,如有需求,可自己拓展)==,然后点击批量导入按钮选择excel目标文件,将数据获取封装到json中。
- 相关操作:
js文件(通过CDN方式引入)
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/xlsx/0.11.5/xlsx.core.min.js"></script>
jsp代码,modal(弹框部分代码,不含css)
<div class="panelCont" style="height: 162px;display: flex;flex-direction: column;justify-content: center;"><div class="panelBtn" style="margin-top: 0px!important;"><form id="addMultiFm"><input type="file" name="file" class="am-form-field" style="display: none;"accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" required></form><div id="batchImportHouse" class="op-btn temp" style="margin-right: 50px!important;">批量导入</div><div id="manualAddHouse" class="op-btn temp" style="margin-right: 0px!important;">手动添加</div></div><a href="/IntellComSys/pub/file/房号模板.xlsx" class="module-download">模板下载</a></div>
modal截图
excel模板截图
js代码,实现获取excel数据,并封装
$("#batchImportHouse").click( function () {var keyFinal = "房屋门号";//头$("input[name='file']").click().change(function(e){ //file的值改变时,请求var files = e.target.files;var fileReader = new FileReader();fileReader.onload = function(ev) {try {var data = ev.target.resultvar workbook = XLSX.read(data, {type: 'binary'}); // 以二进制流方式读取得到整份excel表格对象var rooms = []; // 存储获取到的数据} catch (e) {alertMsg(2, '文件类型不正确, 请重新选择文件');return;}// 表格的表格范围,可用于判断表头是否数量是否正确var fromTo = '';// 遍历没一张sheet并读取内容for (var sheet in workbook.Sheets) {if (workbook.Sheets.hasOwnProperty(sheet)) {fromTo = workbook.Sheets[sheet]['!ref'];if(!fromTo){alertMsg(2, '文件内容为空, 导入失败');return;}rooms = rooms.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));// break; // 如果只取第一张表,就取消注释这行}}var roomName = [];//门号数组var flag = 1;for(var room in rooms){if(getJsonObjLength(rooms[room]) > 1){//excel存在多列alertMsg(2, '内容包含多列,导入失败');flag = 0;}else if(!rooms[room].hasOwnProperty(keyFinal)){alertMsg(2, '表头有误,导入失败');flag = 0;}else{roomName[room] = rooms[room][keyFinal];var nary = roomName.sort();//对卡号进行排序for(var i=0;i<roomName.length;i++){if (nary[i]==nary[i+1]){alertMsg(2,"重复门号:"+nary[i]+ ", 导入失败");flag = 0;break;}}}}if(flag == 1){var param = {};param.staffId = staffId;param.buildingUnitId = localStorage.getItem("buildingUnitId");param.roomName = roomName;//addHouseMethod(param);//调用接口,实现导入,此方法没提供}};// 以二进制方式打开文件fileReader.readAsBinaryString(files[0]);});
});
js工具方法
//返回json的长度
function getJsonObjLength(jsonObj) {var Length = 0;for (var item in jsonObj) {Length++;}return Length;
}