將Excel表格數據導入數據庫

1.jsp頁面獲取導入的文件路徑
       
1.1 
    <tr>
              <th class="th"><span>導入excel表格:</span></th>
              <td   align="left">
                   <input class="hidden" id="arcId" value="${archiveId}"/>
                   <input  align="left" type="file" id="importPath" name="importPath"/>
                   <input type="button"  value="開始導入" onclick="_importExcel();"/><br>
              </td>
     </tr>
 
1.2
   //開始導入Excel表
function _importExcel(){
         var archiveId=$("#arcId").val();
         //獲取導入文件的格式
         var importPath=$("#importPath").val();
         var point = importPath.lastIndexOf(".");  
         var type = importPath.substr(point);  
    if(type==".xls"||type==".XLS"||type==".xlsx"||type==".XLSX"){  
              $.ajaxFileUpload({
                     //處理文件上傳操作的服務器端地址(可以傳參數,已親測可用)
                 url:"${basePath}docAndInfra/importExcel.do?archiveId="+archiveId,
                 secureuri:false,                       //是否啓用安全提交,默認爲false
                 fileElementId:'importPath',           //文件選擇框的id屬性
                 dataType:'json',                       //服務器返回的格式,可以是json或xml等
                 success:function(data, status){        //服務器響應成功時的處理函數
                      if(data.flag){
                           $.messager.alert("操作提示","導入完成!可以選擇文件繼續導入");
               
                      }else{
                           $.messager.alert("操作提示","導入失敗!請確認Excel文件模版格式是否正確!")
                      }                
                 },
                 error:function(data, status, e){ //服務器響應失敗時的處理函數
                         $('#result').html('Excel導入失敗,請重試!!');
                 }
             });      
        }else{
             $.messager.alert("操作提示","導入文件的格式錯誤!");
        }
}
注意:獲取導入文件的路徑需要用到這個js文件,它是根據同名的異步處理方法ajaxFileUpload來處理路徑問題

2.後臺接收請求

/**
 * 開始導入excel表格數據
 * @param archiveId
 * @param importPath
MultipartFile  是處理文件路徑的類,不能單純的使用String類型來接受文件的路徑
 * @return
 */
@RequestMapping("importExcel.do")
@ResponseBody
public Map<String,Object> importExcel(@RequestParam(value="archiveId",required=false)StringarchiveId,@RequestParam(value="importPath")MultipartFile importPath,
HttpServletRequest request, HttpServletResponse response)throws Exception{
 
    boolean flag=docAndInfraService.importExcel(archiveId,importPath,request,response,getCurrentUser());
    Map<String,Object> map=new HashMap<String,Object>();
    map.put("flag", flag);
    return map;
}

3.service 處理請求

3.1 處理方法
/**
  * 將導入的Excel表中的數據插入到數據庫中
  * @param archiveId
  * 插入案卷的ID
  * @param importPath
  * Excel表格的路徑名稱
  * @return
  */
 @Transactional
 public Boolean importExcel(String archiveId,MultipartFile importPath,HttpServletRequest request,
         HttpServletResponse response,CurrentUser currentUser)throws Exception{
  //將Excel上傳到upload文件夾下
  String serverPath=importUpLoad(importPath, response, request);
 
  boolean flag=false;
  String identyNo="";
  Integer retention=null;
  String fcYear="";
  Integer status=1;
  String dirNum="";
  String archiveNo="";
  int index=3;
  if(archiveId!=null&&!archiveId.equals("")){
   DocAndInfraArchive docArchive=findArchiveById(archiveId);
   identyNo=docArchive.getIdentyNo();
   retention=docArchive.getRetention();
   fcYear=docArchive.getFcYear();
   dirNum=docArchive.getDirNum();
   archiveNo=docArchive.getArchiveNo();
   index=2;
  }
   try {  
            // 構造 Workbook 對象,execelFile 是傳入文件路徑(獲得Excel工作區)  
            Workbook book = null;  
            if(serverPath.endsWith("xls") || serverPath.endsWith("XLS")){
             // Excel 2003獲取方法  
                book = new HSSFWorkbook(new FileInputStream(serverPath));
            }
            if(serverPath.endsWith("xlsx") || serverPath.endsWith("XLSX")){
                // Excel 2007獲取方法  
                book = new XSSFWorkbook(new FileInputStream(serverPath));  
            }                          
            // 讀取表格的第一個sheet頁                      
            Sheet sheet = book.getSheetAt(0);  
            // 定義 row、cell  
            Row row;            
            DocAndInfraInner docInner=null;
            if(archiveId==null||archiveId.equals("")){
             fcYear=sheet.getRow(1).getCell(1).toString();
             retention=Integer.parseInt(sheet.getRow(1).getCell(5).toString());
            }
            // 總共有多少行,從0開始  
            int totalRows = sheet.getLastRowNum() ;  
            for (int i = index; i <= totalRows; i++) {
             row = sheet.getRow(i);  
                // 處理空行  
                if(row == null){  
                    continue ;  
                }
             docInner=new DocAndInfraInner();
             String filePath=null;
             if(archiveId!=null&&!archiveId.equals("")){
              docInner.setIdentyNo(identyNo);
              docInner.setRetention(retention);
              docInner.setArcYear(fcYear);          
              docInner.setArchiveId(archiveId);      
           filePath="fileUpLoad"+"\\"+fcYear+"\\"+retention+"\\"+dirNum+"_"+archiveNo;
             }
             if(archiveId==null||archiveId.equals("")){
              docInner.setIdentyNo("ws");
              docInner.setArcYear(fcYear);
              docInner.setRetention(retention);
              filePath="fileUpLoad"+"\\"+fcYear+"\\"+retention+"\\00_"+row.getCell(0).toString();
             }
             docInner.setFilePath(filePath);
             
                docInner.setFondsNum("FE2");
                docInner.setStatus(status);
                docInner.setCreator(currentUser.getUsername());
                docInner.setModifier(currentUser.getUsername());
                docInner.setCreateDate(DateUtils.getNow());
                docInner.setModifyDate(DateUtils.getNow());
                docInner.setFileNum(row.getCell(0).toString());
                docInner.setResponsibility(row.getCell(1).toString());
                docInner.setDocNo(row.getCell(2).toString());
                docInner.setFileName(row.getCell(3).toString());
                docInner.setWrittenTime(row.getCell(4).toString());
                docInner.setStartPage(row.getCell(5).toString());
                docInner.setPageCount(row.getCell(6).toString());
                docInner.setRemark(row.getCell(7).toString());
         
          //確保插入卷內文書的唯一性,存在則跳過!
          DocAndInfraInner doc2=findSameInner(docInner);
          if(doc2!=null){
           continue;
          }
                docAndInfraInnerDao.save(docInner);
                             
            }
            flag=true;
    } catch (FileNotFoundException e) {  
             e.printStackTrace();  
       } catch (IOException e) {  
             e.printStackTrace();  
       }  
  return flag;
 }

3.2 調用的方法

/**
  * 將Excel上傳到項目webapp文件的upload文件夾下
  * @param importPath
  * @param response
  * @param request
  * @return
  * @throws Exception
  */
 @Transactional
 private String importUpLoad(MultipartFile importPath,HttpServletResponse response,HttpServletRequest request)throws Exception{
  Long lTime=new Date().getTime();
  String filePath = request.getSession().getServletContext().getRealPath("upload");
  String savePath=filePath+"/importUpload";
  File file=new File(savePath);
  if(file==null||!file.exists()){
   file.mkdirs();
  }else{
//刪除超過時間的緩存文件
   deleteFile(savePath, lTime);
  }
  request.setCharacterEncoding("UTF-8");
  response.setContentType("text/html;charset=utf-8");
  FileOutputStream os = null;
  InputStream in = importPath.getInputStream();
  os = new FileOutputStream(filePath+"/importUpload/"+importPath.getOriginalFilename());
  byte b[] = new byte[1024];
  while (in.read(b) != -1) {
   os.write(b);
  }
  os.flush();
  in.close();
  os.close();
  return savePath+"/"+importPath.getOriginalFilename();
 }

/**
  * 根據目錄刪除文件
  *
  * @param path
  * @param time
  * @since 2014-6-24
  * @author Sunm
  */
 private void deleteFile(String path, long time) {
  File file = new File(path);
  if (file.isDirectory()) {
   File[] files = file.listFiles();
   if (files == null || files.length == 0) {
    file.delete();
   } else {
    for (File f : files) {
     if (f.isDirectory()) {
      deleteFile(f.getPath(), time);
     }
     if (time != 0) {
      long lastModifyTime = f.lastModified();
      if (time - lastModifyTime <= 1000 * 3600) {
       continue;
      }
     }
     f.delete();
    }
   }
  }
 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章