導入excle數據將excle數據插入到數據庫


實現功能是,用戶可以直接導入對應數據,或者用戶下載模板,填寫數據,導入模板數據。easyui實現

 

前台頁面

                                    {
                                        text : '日清導入',
                                        iconCls : 'icon-print',
                                        handler : function(){
                                            $('#import').dialog('open');
                                        }
                                        
                                    }
        <div id = "import" title="員工信息導入" modal=true draggable=true align="center" class="easyui-dialog" closed=true style="width: 400px">
        <form id="importForm" method="post" enctype="multipart/form-data">
        <table id="importTable" align="center">
        <tr> 
        <td align="center" colspan="2">
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;上傳:<input id = "myFile" name="myFile" type="file"></input>
        </td>
        
         </tr>
        
                
        <tr>
            <td align ="center" colspan="2"><a id="download" href="<%=basePath %>import_template/template-dayrecruit.xls" class="easyui-linkbutton" >模板下載</a>&nbsp;&nbsp;&nbsp;
                        <a id="upload" class="easyui-linkbutton">上傳</a>&nbsp;&nbsp;&nbsp;
                        <a id="importCancel" class="easyui-linkbutton">取消</a>&nbsp;&nbsp;</td>        
        </tr>
        </table>
        </form>
        </div>

以上代碼加顏色的是特別注意的點。上傳文件一定加這些聲明,否則不可實現。點擊模板下載可以直接在我們根路徑下找到模板,並下載。

具體的后台代碼是:

@RequestMapping(value = "/imp", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public @ResponseBody String imp(@RequestParam MultipartFile myFile,//這里會直接以流文件形式接收上傳數據
        HttpServletRequest request, HttpSession session) throws Exception {

    Account account = this.getStaticAccount();
    if (myFile == null || myFile.getSize() == 0) {
        return "未選擇任何文件,請選擇文件后上傳!";
    }
    String fileType = myFile.getOriginalFilename().substring(
            myFile.getOriginalFilename().lastIndexOf("."));
    if (!fileType.equals(".xls") && !fileType.equals(".xlsx")) {
        return "文件格式錯誤,請上傳.xls或.xlsx格式文件!";
    }
    //String path = CommonsMethod.getProjectPath() ;
    String path=request.getSession()
            .getServletContext().getRealPath("/")
            + "/importReserveExcel/";
    String fileattr = CommonsMethod.getNowCorrect2Millisecond()
            + myFile.getOriginalFilename().substring(
                    myFile.getOriginalFilename().lastIndexOf("."));
    final File targetFile = new File(path, fileattr);
    if (!targetFile.exists()) {
        targetFile.mkdirs();
    }
    try {
        myFile.transferTo(targetFile);
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    ArrayList<Object> dataList = new ArrayList<Object>();
    try {
        dataList = dayRecruitService.readExcel(
                targetFile.getAbsolutePath(), 4);
    } catch (Exception e) {
        return e.getMessage();
    }
    try {
        String failImport = dayRecruitService.importDayrecruit(
                dataList, account);
    } catch (RuntimeException e) {
        return e.getMessage();
    } catch (Exception e) {
        return "請仔細核對上傳格式(參考備注)";
    }
    return "上傳成功";
}

private static final String[] headers = new String[] {"日清日期","備注","面試人數","入職人數","招聘企業"};

readExcel代碼:把數據先讀到一個dayrecruit模板中 原因是當前讀的數據不是直接向數據庫中存的數據。

public ArrayList<Object> readExcel(String absolutePath, int i)throws Exception {
        // TODO Auto-generated method stub
        
        ExcelOperations oper = new ExcelOperations();
        ArrayList<Object> list = oper.readExcel(absolutePath,
                Template_DayRecruit.class, columnHeaders,i );
        
        return list;
    }
    
    public static final String[] columnHeaders = { "date",
        "remarks", "viewerNu",
        "entryNu", "customerName"};

正式讀取excle數據代碼為

public ArrayList<Object> readExcel(String filePath, Class entity,
            String[] columnHeads, int noReadSize) throws Exception {
        ArrayList<Method> list = new ArrayList<Method>();
        ArrayList<Object> objs = new ArrayList<Object>();

        try {
            for (int i = 0; i < columnHeads.length; i++) {
                char f = columnHeads[i].charAt(0);
                if (!Character.isUpperCase(f)) {
                    columnHeads[i] = String.valueOf(Character.toUpperCase(f))
                            + columnHeads[i].substring(1);
                }
                Method methodGet = entity.getMethod("get" + columnHeads[i]);
                Method methodSet = entity.getMethod("set" + columnHeads[i], methodGet.getReturnType());
                list.add(methodSet);
            }
            InputStream inputstream = new FileInputStream(filePath);
            Workbook wb = WorkbookFactory.create(inputstream);
            Sheet sheet1 = wb.getSheetAt(0);
            for (int i = 1; i <= sheet1.getLastRowNum() - noReadSize; i++) {
                try {
                    
                    Object obj = entity.newInstance();
                    Cell cell = null;
                    for (int k = 0; k < list.size(); k ++) {                                                
                        cell = sheet1.getRow(i).getCell(k);
                        if(cell.getCellType() == 0){
                        //判斷是否為日期
                        if(HSSFDateUtil.isCellDateFormatted(cell)){
                            SimpleDateFormat sdf = null;  
                            if (cell.getCellStyle().getDataFormat() == HSSFDataFormat  
                                    .getBuiltinFormat("h:mm")) {  
                                sdf = new SimpleDateFormat("HH:mm");  
                            } else {// 日期  
                                sdf = new SimpleDateFormat("yyyy-MM-dd");  
                            }  
                            Date date = cell.getDateCellValue();  
                            cell.setCellValue(sdf.format(date)); 
                         
                        }else{
                                double value = cell.getNumericCellValue();  
                                CellStyle style = cell.getCellStyle();  
                                DecimalFormat format = new DecimalFormat();  
                                String temp = style.getDataFormatString();  
                                // 單元格設置成常規  
                                if (temp.equals("General")) {  
                                    format.applyPattern("#");  
                                }  
                                cell.setCellValue(format.format(value)); 
                               
                        }                                                                
                        }
                        list.get(k).invoke(obj, cell.toString());
                    }
                    objs.add(obj);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new Exception("Excel 文件第" + i + "行格式錯誤");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return objs;
    }

然后調用import方法,里面會驗證需要驗證的數據。如果有一條沒有通過驗證那么所有的數據將會回滾操作。這主要牽扯到了事務管理。

    public String importDayrecruit(List<Object> dataList, Account user)
            throws Exception {
    
        String failImport = "";
        if (dataList != null && dataList.size() > 0) {    
            
            //根據公司user找到對應公司 根據公司找到對應的 招聘企業 根據招聘企業 
            Organization org = dayRecruitDAO.findOrganizationById(user.getOrganization().getId());
            
            List<EnterpriseCustomer> customers = dayRecruitDAO.findAllEnterpriseCustomerByOrg(user.getOrganization().getId());
            
            
            
            for (int i = 0; i < dataList.size(); i++) {
                DayRecruit dayRec = new DayRecruit();
                Template_DayRecruit t_dayRecruit = new Template_DayRecruit();
                t_dayRecruit = (Template_DayRecruit) dataList.get(i);
                dayRec.setWriter(user.getLoginName());
                dayRec.setDatatime(new Date());
                dayRec.setRemarks(t_dayRecruit.getRemarks().trim());
                //dayRec.
                //驗證招聘日期
                if(isValidDate(t_dayRecruit.getDate().trim()) && StringUtils.isNotBlank(t_dayRecruit.getDate().trim())){                                          
                     dayRec.setDate(t_dayRecruit.getDate().toString());
                    
                }else throw new RuntimeException("第" + (i + 2)
                        + "行填寫招聘日清日期有誤,請重新確定");        
                //驗證填寫人
/*                if(StringUtils.isNotBlank(dayRec.getWriter()) && dayRec.getWriter().equals(user.getUserName())){
                    dayRec.setWriter(dayRec.getWriter().trim());                    
                }
                else{
                    throw new RuntimeException("第" + (i + 2)
                            + "行填寫輸入人有誤,請填寫您的登錄賬號,請重新確定");
                }*/                                                
                //驗證面試人數
                if(isNumeric(t_dayRecruit.getViewerNu().trim()) && StringUtils.isNotBlank(t_dayRecruit.getViewerNu().trim())){                    
                    dayRec.setViewerNu(t_dayRecruit.getViewerNu().trim());                    
                }
                else throw new RuntimeException("第" + (i + 2)
                        + "行填寫面試人數有誤,請重新確定");
                //驗證入職人數
                if(isNumeric(t_dayRecruit.getEntryNu().trim()) && StringUtils.isNotBlank(t_dayRecruit.getEntryNu().trim())){
                    
                int  re =     Double.valueOf(t_dayRecruit.getEntryNu().trim()).compareTo(Double.valueOf(t_dayRecruit.getViewerNu().trim()));
                  if(re <1){                                        
                    dayRec.setEntryNu(t_dayRecruit.getEntryNu().trim());    }
                  else {
                      throw new RuntimeException("第" + (i + 2)
                                + "行入職人數大於面試人數,請重新確定");
                }
                }
                else throw new RuntimeException("第" + (i + 2)
                        + "行填寫入職人數有誤,請重新確定");
                
                //驗證招聘企業  從模板中獲取招聘企業的名字 查詢出 此公司所有的招聘企業 對應的話  取 招聘企業這個對象賦值給dayR

                // 驗證所屬公司
                if(StringUtils.isNoneBlank(t_dayRecruit.getCustomerName().trim())){
                    boolean isOK = false;
                    if(customers != null && customers.size()>0){
                    for(int j =0;j<customers.size();j++){
                    if(customers.get(j).getEnterpriseName().equals(t_dayRecruit.getCustomerName().trim())){
                        
                        dayRec.setCustomer(customers.get(j));
                        isOK = true;
                        break;//跳出當前循環
                    }
                    
                }
                
                }
                    if (!isOK) {
                        throw new RuntimeException("第" + (i + 2)
                                + "行招聘企業輸入有誤,請重新確定");
                    }
                }
                
                dayRecruitDAO.add(dayRec);
            }
        } else {
            throw new RuntimeException("導入數據為空");
        }
        return failImport;
    }

這樣數據就插入到對應數據庫。完成導入操作。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM