1. 程式人生 > >.xls;*.xlsx檔案的匯入(可以匯入多條資料)

.xls;*.xlsx檔案的匯入(可以匯入多條資料)

jsp頁面:

<LINK href="${basePath}plugins/uploadify/uploadify.css" type="text/css" rel="stylesheet" />
<script language="javascript" type="text/javascript">
    //防止客戶端快取檔案,造成uploadify.js不更新,而引起的“喔唷,崩潰啦”  
    document.write ("<script type='text/javascript' " + "src='${basePath}plugins/uploadify/jquery.uploadify.min.js?
" + new Date () + "'><\/script>"); </script> <script type="text/javascript">
//匯入excel $(function(){ $(
"#uploadFile").uploadify({ buttonClass:'', fileSizeLimit: '20480KB', uploader: '${basePath}core/upload!uploadFile.action', // 伺服器端處理地址 swf: '
${basePath}js/uploadify/uploadify.swf', // 上傳使用的 Flash buttonText: "匯入", buttonCursor: 'hand', fileObjName: 'uploadify',// 上傳引數名稱 後臺action裡面的屬性uploadify fileTypeExts: "*.xls;*.xlsx", // 副檔名 fileTypeDesc: "請選擇 檔案格式", removeTimeout:1, //
檔案說明 auto: true, // 選擇之後,自動開始上傳 multi: false, // 是否支援同時上傳多個檔案 queueSizeLimit: 1, // 允許多檔案上傳的時候,同時上傳檔案的個數 queueID:'queueID', onUploadSuccess:function(file, data, response){ var data =jQuery.parseJSON(data); if(data.error == 1){ ldDialog.alert(data.message); }else{ $.ajax({ url:"${basePath}uploadDocumentAction/uploadDocument!insertDrawWorkerMany.action", type:"post", dataType:"json", data:{filePath:data.url,fileName:data.newFileName,crId:"${crId}",dchId:"",chGxId:""}, async:false, success:function(r){ if(r.code=="success"){ ldDialog.tips ("匯入成功!"); document.pagerForm.submit (); }else{ if(r.message!="" && r.message!=null){ ldDialog.tips (r.message,"5"); }else{ ldDialog.tips ("匯入失敗!"); } } } }); } } }); }); </script> <input type="button" id="uploadFile" class="ldBtnGray" value="匯入"/> <a href="${basePath}upload/template/template11.xls" download="template11.xls">
<span style='float:right;margin-right:20px;margin-top:10px;font-size:18px;color:#2891d2;'>模板下載</span></a>

java類:

    @RequestMapping("core/upload!uploadFile.action")
    public void uploadFile(@RequestParam(value = "uploadify", required = false) MultipartFile uploadify,HttpServletRequest request,HttpServletResponse response,ModelMap modelMap) throws Exception {

        @SuppressWarnings("deprecation")
        String savePath = request.getRealPath("/")+ "/" + "upload/";
        String saveUrl = "upload/";
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("file", "pdf,rar,zip,7z,gif,jpg,jpeg,png,bmp,doc,docx,xlsx,xls");
        //extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("csv", "csv");
         int uploadMaxSize =Integer.valueOf(optionService.getByOptionName(CoreValue.OPTION_UPLOAD_MAX_SIZE).getOptionValue());
        long maxSize = Long.valueOf(String.valueOf(uploadMaxSize)).longValue();
        String maxSizeKb = StringUtil.formatNumber(new Double(maxSize / 1024L),"0");
        response.setContentType("text/html; charset=UTF-8");
        String jsonString = "";
        if (!ServletFileUpload.isMultipartContent(getRequest())) {
            jsonString = getError("請選擇檔案。");
            response.getWriter().println(jsonString);
            return;
        }

        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
            jsonString = getError(savePath + "上傳目錄不存在。");
            response.getWriter().println(jsonString);
            return;
        }

        if (!uploadDir.canWrite()) {
            jsonString = getError("上傳目錄沒有寫許可權。");
            response.getWriter().println(jsonString);
            return;
        }

        String dirName = getRequest().getParameter("dir");
        if (dirName == null) {
            dirName = "file";
        }
        if (!extMap.containsKey(dirName)) {
            jsonString = getError("目錄名不正確。");
            response.getWriter().println(jsonString);
            return;
        }

        savePath = savePath + dirName + "/";
        saveUrl = saveUrl + dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String ymd = sdf.format(new Date());
        savePath = savePath + ymd + "/";
        saveUrl = saveUrl + ymd + "/";
        File dirFile = new File(savePath);

        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        String fileName = uploadify.getOriginalFilename();
        long fileSize = uploadify.getSize();
        if (fileSize > maxSize) {
            jsonString = getError("上傳檔案大小超過限制。最大為" + maxSizeKb + "kb");
            response.getWriter().println(jsonString);
            return;
        }

        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            
        if (!Arrays.asList(((String) extMap.get(dirName)).split(",")).contains(fileExt)) {
            jsonString = getError("不允許的上傳檔案型別。");
            response.getWriter().println(jsonString);
            return;
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_"+ new Random().nextInt(1000) + "." + fileExt;
        File uploadedFile = null;
        try {
            uploadedFile = new File(savePath, newFileName);
            if(uploadedFile.exists()){
                
            }
            if(!uploadedFile.exists()){
                uploadedFile.mkdirs();
            }
            uploadify.transferTo(uploadedFile);
        } catch (Exception e) {
            jsonString = getError("上傳檔案失敗。");
            response.getWriter().println(jsonString);
            return;
        }
        JSONObject obj = new JSONObject();
        obj.put("error", Integer.valueOf(0));
        obj.put("url", saveUrl + newFileName);
        obj.put("newFileName", newFileName);
        obj.put("fileName", fileName);
        jsonString = obj.toJSONString();
        response.getWriter().println(jsonString);
    }

    private String getError(String message) {
        JSONObject obj = new JSONObject();
        obj.put("error", Integer.valueOf(1));
        obj.put("message", message);
        return obj.toJSONString();
    }