<%@ page language="java" pageEncoding="UTF-8"%> <%@ page import="java.util.List,com.atsc.common.GlobalConstant,com.atsc.struts.system.UserProfile"%> <%@ taglib uri="/WEB-INF/struts-html" prefix="html"%> <%@ taglib uri="/WEB-INF/struts-bean" prefix="bean"%> <%@ taglib uri="/WEB-INF/jstl/core" prefix="c"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; request.setAttribute("basePath", basePath); %> <!DOCTYPE html> <html> <head> <base href="<%=basePath%>" target="_self"> <title>導入數據</title> <link rel="stylesheet" type="text/css" href="${basePath }css/style_yellow.css"> <link rel="stylesheet" type="text/css" href="${basePath }css/jquery-ui.css"> <script type="text/javascript" src="${basePath }js/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="${basePath }js/htcommon.js"></script> <script type="text/javascript"> jQuery(document).ready( function() { jQuery("#imp_btn").bind( "click", function() { var filename = document.getElementById("uploadFile").value; if (filename == "") { alert("請選擇Excel文件"); return false; } var fileExp = filename.substring(filename.lastIndexOf(".") + 1).toLocaleLowerCase(); if (fileExp != "xlsx" && fileExp != "xls") { alert("請選擇(.xlsx或.xls)類型的文件"); return; } if (!confirm("確認導入?")) { return; } jQuery("#action").val("impExcel"); jQuery("#mess_div").show(); jQuery("form").submit(); }); }); </script> </head> <body style="margin: 0px"> <div id="mess_div" class="ui-widget-overlay ui-front" style="text-align: center;padding-top:100px;display: none;width:100%"> <img src="images/loading/loding.gif" style="vertical-align: middle;"> <strong style="color: black;">正在導入,請稍等...</strong> </div> <html:form action="mdAcceptSaveOrMerger" enctype="multipart/form-data"> <html:hidden property="action" styleId="action" /> <html:hidden property="mainId" styleId="mainId" /> <br /> <table class="cond" cellpadding="5px"> <tbody> <tr> <td> <span><strong>器具主數據收集表</strong></span> <html:file property="uploadFile" styleId="uploadFile" style="height:22px;width:300px"></html:file> <span style="color: red">(文件格式:.xlsx或.xls)</span> </td> </tr> </tbody> </table> <div style="text-align: center;"> <input type="button" class="button" value="Excel導入" id="imp_btn" /> <input type="button" class="button" value="關閉" onclick="window.close();" /> </div> <br /> <html:messages id="alertMess" property="alertMess" message="true"> <table style="width:100%"> <tr> <td style="vertical-align: top;text-align:right;width:30px;"><img src="images/prompt/f.gif" style="vertical-align: middle;"></td> <td> <div style="color: red;">${alertMess}</div> </td> </tr> </table> </html:messages> </html:form> </body> </html>
以上是jsp頁面javascript
如下是action 中的準備代碼css
InputStream inputStream = mdAcceptEditForm.getUploadFile().getInputStream();//獲取 jsp頁面的文件流 Workbook wb = null;//定義一個工做空間 //判斷是什麼版本的Excel boolean isExcel2003 = mdAcceptEditForm.getUploadFile().getFileName().matches("^.+\\.(?i)(xls)$"); if (isExcel2003) { POIFSFileSystem fs = new POIFSFileSystem(inputStream); wb = new HSSFWorkbook(fs); } else { wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(inputStream); } Sheet sheet = wb.getSheetAt(0);//獲取第一sheet頁 StringBuffer c = new StringBuffer(); String mess = MD_ACCEPT_SERVICE.importData(sheet, currentUser, c,mianId);//導入到數據庫及驗證的具體方法 如下會有詳細解釋 同時返回驗證的提示信息 if (StringUtils.isNotBlank(mess)) { messages.add("alertMess", new ActionMessage(mess, false)); this.addMessages(request, messages); } else { //設置返回到頁面的js提示信息 response.setCharacterEncoding("utf-8"); response.getWriter().write("<script>alert('導入器具數據收集表成功');window.close();</script>"); response.flushBuffer(); return null; }
importData的具體html
public String importData(Sheet sheet, UserProfile currentUser, StringBuffer c,String mainId) throws Exception { String mess = "";//定義消息 Connection conn = null; try { conn = getConnection(); conn.setAutoCommit(false); int rows = sheet.getLastRowNum();//獲取行數 List propList = new ArrayList();//定義list數組 封裝excel數據對象 /** * 檢測表頭 */ Row titleRow = sheet.getRow(0); if (titleRow == null) { conn.rollback(); return "沒有標題行!,第1行應爲列標題行"; } //定義一個實體類分別爲兩個字段 PropName保存excel表頭信息 FieldName保存數據庫字段信息 EquipPropDTO qjbh = new EquipPropDTO(); qjbh.setPropName("器具名稱"); qjbh.setFieldName("MD_NAME"); propList.add(qjbh); ;;;;;;;; Map propNameMap = new HashMap(); //定義map來封裝 以上信息 EquipPropDTO 的信息 for (int i = 0; i < propList.size(); i++) { EquipPropDTO dto = (EquipPropDTO) propList.get(i); propNameMap.put(dto.getPropName(), dto); } //定義消息主信息 String messTip = "<strong> 器具導入收集表中第[ @line ]行:</strong><br/>"; /** * 封裝數據 */ int line = 0; List<Map<String, Object>> importList = new ArrayList<Map<String, Object>>(); //循環獲取每一行的數據 for (int r = 1; r <= rows; r++) { line = r + 1; //獲得第一行的數據 Row row = sheet.getRow(r); //建立讀取數據的方式 excelReadRow這個方法如下會有詳細說明 Map mdMap = this.excelReadRow(row, titleRow, propNameMap); //對字段名稱進行驗證 這裏的驗證能夠有多樣 在此只列出其中一種 if (StringUtils.isBlank(ObjectUtils.toString(mdMap.get("MD_NAME")))) { mess += "【器具名稱】不能爲空。"; break; } //把獲取到的數據封裝到list<map>對象中 importList.add(mdMap); } //若是以上驗證消息不爲空 則證實有錯誤信息 結束方法 返回提示信息 if (StringUtils.isNotBlank(mess)) { conn.rollback(); return messTip.replaceFirst("@line", String.valueOf(line)) + mess; } //此處是本人保存excel中信息的方法 importList中有多少個對象 就說明excel中有多少條數據 for(int i=0;i<importList.size();i++){ MD_ACCEPT_DAO.saveItem(conn,importList.get(i),mainId,main); } conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { conn.rollback(); mess = "導入報表格式錯誤,請檢查。"; throw e; } finally { close(conn); } return mess; }
如下是對excelReadRow方法的詳細介紹java
/** * 讀取excel數據 * @param row * @param rowTitle * @param propNameMap * @return */ public Map<String, Object> excelReadRow(Row row, Row rowTitle, Map<String, EquipPropDTO> propNameMap) { Map<String, Object> mdMap = new HashMap<String, Object>(); int dataCols = rowTitle.getLastCellNum();//獲取每一行有多少個格子 for (int i = 0; i < dataCols; i++) { //把獲取到的數據 rowTitle.getCell(i)是獲得表頭名稱 getCellStringValue是獲取對應表頭設置的數據格式封裝到EquipPropDTO 對象中 EquipPropDTO prop = (EquipPropDTO) propNameMap.get(ExcelUtil.getCellStringValue(rowTitle.getCell(i))); if (prop != null) { //獲取格子中的數據 Object v = ExcelUtil.getCellStringValue(row.getCell(i)); /*if (prop.getFieldName().contains("DATE")) { v = v.toString().replace("-", ""); }*/ //報數據存到map mdMap.put(prop.getFieldName(), v); } } return mdMap; } //如下是對getCellStringValue的詳細解釋 /** * 獲取Excel表格內容 * * @param cell * @return */ public static String getCellStringValue(Cell cell) { if (cell == null) return ""; String value = ""; double numericValue = 0; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { // 若是是Date類型則 ,獲取該Cell的Date值 value = HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString(); } numericValue = cell.getNumericCellValue(); if (numericValue - (int) numericValue == 0) value = String.valueOf((int) numericValue); else { // value = String.valueOf(numericValue); BigDecimal bd = new BigDecimal(String.valueOf(cell.getNumericCellValue())); bd.setScale(2, BigDecimal.ROUND_HALF_UP); value = bd.toString(); } break; case HSSFCell.CELL_TYPE_FORMULA: try { value = cell.getStringCellValue(); } catch (Exception e1) { try { value = String.valueOf(cell.getNumericCellValue()); } catch (Exception e2) { value = "error"; } } break; case HSSFCell.CELL_TYPE_STRING: value = cell.getStringCellValue().trim(); break; case HSSFCell.CELL_TYPE_BLANK: value = ""; break; } return value.trim(); }