給用戶下載EXCEL模板 ,而後用戶按模板填寫進行批量新增。javascript
分析:其實就是前臺發送請求後,而後下載服務器內固定地址的文件;java
請求方式:web
function excelDownload(){
window.open("${basePath}terwarning/terminal/downloadExcle.json")
}
複製代碼
web層的代碼:數據庫
/** * 下載EXCEL模板 * * @param request * @return * @throws Exception */
@RequestMapping("downloadExcle.json")
public ResponseEntity<byte[]> downloadExcle(HttpServletRequest request)
throws Exception {
ServletContext servletContext = request.getServletContext();
String fileName = "設備新增模板.xls";
String realPath = servletContext.getRealPath("/attached/" + fileName);// 獲得文件所在位置
InputStream in = new FileInputStream(new File(realPath));// 將該文件加入到輸入流之中
byte[] body = null;
body = new byte[in.available()];// 返回下一次對此輸入流調用的方法能夠不受阻塞地今後輸入流讀取(或跳過)的估計剩餘字節數
in.read(body);// 讀入到輸入流裏面
fileName = new String(fileName.getBytes("gbk"), "iso8859-1");// 防止中文亂碼
HttpHeaders headers = new HttpHeaders();// 設置響應頭
headers.add("Content-Disposition", "attachment;filename=" + fileName);
HttpStatus statusCode = HttpStatus.OK;// 設置響應嗎
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body,
headers, statusCode);
return response;
}
複製代碼
分析:apache
1.須要接收EXCEL文件 ,因此須要文件上傳json
2.須要解析EXCEL文件, 這裏要用到apache的poi後端
3.解析到的數據提交到數據庫,完成新增數組
注意:服務器
1.爲了方便用戶,這裏須要進行批量文件上傳。app
2.EXCEL裏有幾行數據就要新增幾條數據到數據庫,因此這裏是批量新增提交, 後臺要用for 循環添加。
3. 數據校驗 ,每一個字段必須都要作校驗, 成功後方可新增提交;
4. 若是有一條數據校驗失敗,全部的數據都不容許新增, 要麼所有都新增成功,要麼所有新增失敗, 保證用戶一次操做的一致性,完整性。
模板示例:
前臺文件上傳form表單代碼:
<form id="myFormId"
action="${basePath}terwarning/terminal/excelAdd.save" method="post"
target="frmright">
<div class="box1" whiteBg="true">
<table id="fileList" class="tableStyle" formMode=transparent>
<tr>
<td width="40%">選擇模板:</td>
<td><input type="file" name="files" multiple="multiple"
onchange="filechange(files)" /></td>
</tr>
<tr>
<td>所屬組織:</td>
<td><div class="selectTree validate[required]"
name="orgData.keyId"
url="${basePath}common/exclude/queryOrgListAndSub.json"
selectedValue="${entity.orgData.keyId }"></div> <span
class="star">*</span></td>
</tr>
<tr>
<td colspan="2"><input id="submitBut" type="button" value="提交" />
<input type="button" value="取消" onclick="quiDialog.close()" /></td>
</tr>
</table>
</div>
</form>
複製代碼
JAVA後端邏輯:
/** * EXCEL新增 * @RequestParam("file") MultipartFile file, HttpServletRequest * request) * * @return * @throws @throws * @throws Exception */
@RequestMapping("excelAdd.save")
public ResponseEntity<String> excelAdd( @RequestParam("orgData.keyId") Integer orgId, @RequestParam("files") MultipartFile[] files, HttpServletRequest request) throws Exception {
//此集合用於存放EXCEL每一條的值
List<TerminalData> paramList = new ArrayList<TerminalData>();
MessageModel messageModel = new MessageModel();//視圖容器 ,非核心邏輯
LoginUserData loginUserData = CommonUtil.getCurrentUserData(request);
UserData userData = loginUserData.getUserData();//得到當前登錄人對象
// 判斷file數組不能爲空而且長度大於0
if (files != null && files.length > 0) {
// 判斷文件是不是.xls的文件
for (int i = 0; i < files.length; i++) {
String string = files[i].getOriginalFilename();
String xlString = string.substring(string.length() - 3, string.length());
if (xlString.equals("xls") || xlString.equals("XLS")) {
} else {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("上傳時請使用有效的EXCEL模板文件");
return PrintUtil.printResponseEntity(messageModel);
}
}
// 循環解析EXCEL ,並完成數據校驗,最後把新增對象add到List裏
for (int i = 0; i < files.length; i++) {
// 上傳文件操做
MultipartFile file = files[i];
String excelPath = request.getSession().getServletContext().getRealPath("/") + "attached/add.xls";
file.transferTo(new File(excelPath));//
// 解析EXCEL sheet.getRow()獲取行
InputStream inputStream = new FileInputStream(excelPath);
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
int rowNum = sheet.getPhysicalNumberOfRows();//得到總行數
int colNum = row.getPhysicalNumberOfCells();//得到總列數
//對每一行的數據進行校驗 , 放進一個List
for (int j = 1; j < rowNum; j++) {
row = sheet.getRow(j);
if (row != null) {
TerminalData terminalData = new TerminalData();
OrgData orgData = new OrgData();
orgData.setKeyId(orgId);
terminalData.setOrgData(orgData);
terminalData.setStasus(0);
if (row.getCell(0) == null ||row.getCell(0).equals("")) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("終端名稱是必填項");
return PrintUtil.printResponseEntity(messageModel);
}
if (row.getCell(1) == null ||row.getCell(1).equals("")) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("終端負責人是必填項");
return PrintUtil.printResponseEntity(messageModel);
}
if (row.getCell(2) == null ||row.getCell(2).equals("")) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("IP地址是必填項目");
return PrintUtil.printResponseEntity(messageModel);
}
if ( row.getCell(3) == null ||row.getCell(3).equals("")) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("MAC地址是必填項");
return PrintUtil.printResponseEntity(messageModel);
}
if ( row.getCell(4) == null ||row.getCell(4).equals("")) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("硬盤序列號是必填項");
return PrintUtil.printResponseEntity(messageModel);
}
if (row.getCell(5) == null ||row.getCell(5).equals("")) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("CPU是必填項");
return PrintUtil.printResponseEntity(messageModel);
}
//由於EXCEL文件裏,用.getStringCellValue()方法讀取數字類型會報錯, 這裏作防止報錯處理
Cell numCell0 = row.getCell(0);
if (numCell0 != null) {
numCell0.setCellType(Cell.CELL_TYPE_STRING);
}
String cell0 = numCell0.getStringCellValue();
Cell numCell1 = row.getCell(1);
if (numCell1 != null) {
numCell1.setCellType(Cell.CELL_TYPE_STRING);
}
String cell1 = numCell1.getStringCellValue();
Cell numCell2 = row.getCell(2);
if (numCell2 != null) {
numCell2.setCellType(Cell.CELL_TYPE_STRING);
}
String cell2 = numCell2.getStringCellValue();
Cell numCell3 = row.getCell(3);
if (numCell3 != null) {
numCell3.setCellType(Cell.CELL_TYPE_STRING);
}
String cell3 = numCell3.getStringCellValue();
Cell numCell4 = row.getCell(4);
if (numCell4 != null) {
numCell4.setCellType(Cell.CELL_TYPE_STRING);
}
String cell4 = numCell4.getStringCellValue();
Cell numCell5 = row.getCell(5);
if (numCell5 != null) {
numCell5.setCellType(Cell.CELL_TYPE_STRING);
}
String cell5 = numCell5.getStringCellValue();
if(cell0.equals("")||cell0.length()==0&&
cell1.equals("")||cell1.length()==0&&
cell2.equals("")||cell2.length()==0&&
cell3.equals("")||cell3.length()==0&&
cell4.equals("")||cell4.length()==0&&
cell5.equals("")||cell5.length()==0){
}else {
if (cell0.equals("")||cell0.length()==0) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("終端名稱是必填項");
return PrintUtil.printResponseEntity(messageModel);
}
if (cell1.equals("")||cell1.length()==0) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("終端負責人是必填項");
return PrintUtil.printResponseEntity(messageModel);
}
if (cell2.equals("")||cell2.length()==0) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("IP地址是必填項目");
return PrintUtil.printResponseEntity(messageModel);
}
if (cell3.equals("")||cell3.length()==0) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("MAC地址是必填項");
return PrintUtil.printResponseEntity(messageModel);
}
if (cell4.equals("")||cell4.length()==0) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("硬盤序列號是必填項");
return PrintUtil.printResponseEntity(messageModel);
}
if (cell5.equals("")||cell5.length()==0) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("CPU是必填項");
return PrintUtil.printResponseEntity(messageModel);
}
}
//放進對象後add到List
terminalData.setHostName(cell0);
terminalData.setMasterName(cell1);
terminalData.setIp(cell2);
terminalData.setMac(cell3);
terminalData.setHardDisk(cell4);
terminalData.setCpu(cell5);
terminalData.setType("1");
terminalData.setCreateby(userData);
terminalData.setDelflag("F");
terminalData.setCreatetime(new Date());
paramList.add(terminalData);
} else {
break;
}
}
}
TerminalData terminalData = new TerminalData();
terminalData.setDelflag("F");
//查詢數據庫已有所有設備,驗證IP的MAC地址的惟一性 ,最後刪除值所有爲空的條目;
List<TerminalData> termList = terminalService.queryList(terminalData);
for (int i = 0; i < paramList.size(); i++) {
if (!paramList.get(i).getHostName().equals("") && paramList.get(i).getHostName() != null
&& !paramList.get(i).getMasterName().equals("") && paramList.get(i).getMasterName() != null
&& !paramList.get(i).getIp().equals("") && paramList.get(i).getIp() != null
&& !paramList.get(i).getMac().equals("") && paramList.get(i).getMac() != null
&& !paramList.get(i).getHardDisk().equals("") && paramList.get(i).getHardDisk() != null
&& !paramList.get(i).getCpu().equals("") && paramList.get(i).getCpu() != null) {
String ipString = paramList.get(i).getIp();
String macString = paramList.get(i).getMac();
if (ipString.equals("") || ipString == null || macString.equals("") || macString == null) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("MAC地址和IP地址是必填的");
return PrintUtil.printResponseEntity(messageModel);
}
for (TerminalData term : termList) {
if (ipString.equals(term.getIp())) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("此IP地址已經存在,IP重複爲" + ipString);
return PrintUtil.printResponseEntity(messageModel);
} else if (macString.equals(term.getMac())) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("此MAC地址已經存在,MAC地址重複爲" + macString);
return PrintUtil.printResponseEntity(messageModel);
}
}
} else {
paramList.remove(i);
i--;
}
}
//驗證全部EXCEL文件內是否有IP地址和MAC地址的重複
for (int i = 0; i < paramList.size(); i++) {
for (int j = 0; j < paramList.size(); j++) {
if (i == j) {
} else {
if (paramList.get(i).getIp().equals(paramList.get(j).getIp())) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("EXCEL內IP地址不能重複,重複的IP爲:" + paramList.get(i).getIp());
return PrintUtil.printResponseEntity(messageModel);
}
if (paramList.get(i).getMac().equals(paramList.get(j).getMac())) {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("EXCEL內MAC地址不能重複,重複的MAC爲:" + paramList.get(i).getMac());
return PrintUtil.printResponseEntity(messageModel);
}
}
}
}
//終於完成了全部的鹽城
// 最後 循環List 完成新增操做
for (TerminalData param : paramList) {
terminalService.addOrUpdateData(param);
}
} else {
messageModel.setOperFlag(ConstantData.OPER_ERROR);
messageModel.setMessage("請選擇有效的xls模板文件");
return PrintUtil.printResponseEntity(messageModel);
}
messageModel.setOperFlag(ConstantData.OPER_SUCCESS);
messageModel.setMessage("操做成功");
return PrintUtil.printResponseEntity(messageModel);
}
複製代碼