JAVA實現Excel批量導入


 

一、模板下載:

先將模板放在項目WebRoot下的download文件夾下:

 

/**
     * @Title: downloadFile 
     * @Description: 模板下載 (網絡地址)
     * @param @param id 
     * @param @param url
     * @param @param fileName
     * @param @param response
     * @param @param request
     * @param @throws Exception
     * @return void
     * @throws
     */
    @RequestMapping(value = "/downloadFile")
    public void downloadFile(String url, String fileName, 
            HttpServletResponse response,HttpServletRequest request) throws Exception{
        
        //要對文件名稱進行編碼
        fileName = java.net.URLEncoder.encode(fileName,"utf-8");
        response.addHeader("Content-Disposition","attachment;filename=" + fileName+";filename*=utf-8''"+fileName);    
        response.setContentType("application/octet-stream"); //設置文件MIME類型  
        
        OutputStream out =null;
        InputStream  in=null;
        
        //獲取網站部署路徑(通過ServletContext對象),用於確定下載文件位置,從而實現下載  
        //String path = request.getServletContext().getRealPath("/"); 
        //url = path + "download\\" + "我的客戶導入模板.xls";
        
        try {
            
            URL urlPath = new URL(url);// 創建URL對象
            in = urlPath.openStream();// 獲取url中的輸入流
            out = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(in);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            
            byte[] buff = new byte[20480];
            int b = 0;
            while (-1 != (b = bis.read(buff))) {
                bos.write(buff, 0, b);
            }
            bis.close();
            bos.flush();
            bos.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        
        finally {
            if(out!=null)out.close();
            if(in!=null)in.close();
        }
    }
View Code

 

 

/**
     * 
     * @Title: download 
     * @Description: 下載本地文件
     * @param @param path
     * @param @param response
     * @param @param request
     * @return void
     * @throws
     */
    @RequestMapping(value = "/download")
    public void download(String type, HttpServletResponse response, HttpServletRequest request) {
        
        User u = getUser(request.getSession());//SessionUtils.getUser(request.getSession());
        
        //獲取網站部署路徑(通過ServletContext對象),用於確定下載文件位置,從而實現下載  
        //path = request.getServletContext().getRealPath("/") + "download\\" + "我的客戶導入模板.xls";
        String path = request.getServletContext().getRealPath("/");  
        
        List<BasedataResp> list1 = null;
        List<BasedataResp> list2 = null;
        QueryBasedataParam param1 = new QueryBasedataParam();
        QueryBasedataParam param2 = new QueryBasedataParam();
        param1.setCorpId(Long.valueOf(u.getCorpId()));
        param2.setCorpId(Long.valueOf(u.getCorpId()));
        
        String fileName = "";
        if("1".equals(type)){
            
            fileName = "我的客戶導入模板";
            param1.setLabel("custom_status"); //客戶狀態
            param2.setLabel("custom_level"); //客戶分級
        } else if("2".equals(type)){
            
            fileName = "客戶關聯聯系人導入模板";
            param1.setLabel("contacts_role"); //角色關系
            param2.setLabel("contacts_relation"); //親密程度
        }
        String url = path + "download\\" + fileName + ".xls";
        
        try {  
            
            if(param1.getLabel()!=null && !"".equals(param1.getLabel())){
                list1 = basedataService.selectBasedataInfo(param1); //查詢系統標簽 
                list2 = basedataService.selectBasedataInfo(param2); //查詢系統標簽 
                write(url, list1, list2);
            }
            ExcelExportUtil.getExcel(url, fileName, response); //下載sheet
            
        } catch (Exception e) {  
            System.out.println(e.getMessage());
        }  
    }
    
    /**
     * 
     * @Title: write 
     * @Description: 向已存在的Excel寫入數據 
     * @param @param file
     * @param @param list
     * @param @param list2
     * @param @return
     * @return String
     * @throws
     */
    private String write(String file, List<BasedataResp> list, List<BasedataResp> list2) {
        
        try {
            
            FileInputStream fs = new FileInputStream(file);  //獲取已有的Excel  
            POIFSFileSystem ps = new POIFSFileSystem(fs);  //使用POI提供的方法得到excel的信息   
            HSSFWorkbook wb = new HSSFWorkbook(ps);    
            HSSFSheet sheet1 = wb.getSheetAt(0);  //獲取第一個工作表,一個excel可能有多個工作表 
            HSSFSheet sheet2 = wb.getSheetAt(1); //獲取第二個sheet
            HSSFSheet sheet3 = wb.getSheetAt(2); //獲取第三個sheet
            
            sheet2.removeRow(sheet2.getRow(0));
            sheet3.removeRow(sheet3.getRow(0));
            
            FileOutputStream out = new FileOutputStream(file);  //向d://test.xls中寫數據
            
            HSSFRow row;
       //向第二個sheet寫入數據(第一個sheet中的下拉選項)
for (int i = 0; i < list.size(); i++) { row = sheet2.createRow((short)(i)); //創建行 row.createCell(0).setCellValue(list.get(i).getName()); //設置第一個(從0開始)單元格的數據 }
       //向第三個sheet寫入數據(第一個sheet中的下拉選項)  HSSFRow row2;
for (int i = 0; i < list2.size(); i++) { row2 = sheet3.createRow((short)(i)); //創建行 row2.createCell(0).setCellValue(list2.get(i).getName()); //設置第一個(從0開始)單元格的數據 } out.flush(); wb.write(out); out.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return "success"; }

 

/**
     * 
     * @Title: getExcel 
     * @Description: 下載指定路徑的Excel文件 
     * @param @param url 文件路徑
     * @param @param fileName  文件名
     * @param @param response
     * @return void
     * @throws
     */
    public static void getExcel(String url, String fileName, HttpServletResponse response){
        
         try {  
            
            //1.設置文件ContentType類型,這樣設置,會自動判斷下載文件類型  
            response.setContentType("multipart/form-data");  
            
            //2.設置文件頭:最后一個參數是設置下載文件名  
            response.setHeader("Content-Disposition", "attachment;filename="  
                    + new String(fileName.getBytes("gb2312"), "ISO-8859-1") + ".xls"); //支持中文文件名
            
            //通過文件路徑獲得File對象
            File file = new File(url);  
            
            FileInputStream in = new FileInputStream(file);  
            //3.通過response獲取OutputStream對象(out)  
            OutputStream out = new BufferedOutputStream(response.getOutputStream());  
            
            int b = 0;  
            byte[] buffer = new byte[2048];  
            while ((b=in.read(buffer)) != -1){  
                out.write(buffer,0,b); //4.寫到輸出流(out)中  
            }  
            
            in.close();
            out.flush(); 
            out.close();  
            
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }
    

 

模板截圖:

 

二、通過Excel模板導入數據:

    /**
     * 
     * @Title: impExcel 
     * @Description: 批量導入客戶信息
     * @param @param request
     * @param @param response
     * @param @return
     * @return String
     * @throws
     */
    @RequestMapping("impExcel")
    @ResponseBody
    public String impExcel(MultipartHttpServletRequest request,HttpServletResponse response){
        
        ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CustomConstants.CUSTOM_SELECT_EXCEPTION,"導入客戶信息失敗",null);
        
        MultipartFile file = request.getFile("file");
        ExcelReader er = new ExcelReader();
        int count =0;
        int error =0;
        int success = 0;
        
        List<Custom> list_ = new ArrayList<Custom>();
        User u = getUser(request.getSession());//SessionUtils.getUser(request.getSession());
        Long corpId = Long.valueOf(u.getCorpId());
        Date date = new Date();
        String returnMsg = "";
        int index = 1;
        
        try {
            
            List<Map<Integer,String>> list = er.readExcelContentByList(file.getInputStream()); //讀取Excel數據內容
            count = list.size();
            
            for(Map<Integer,String> map : list){
                
                if(map.get(0)==null || "".equals(map.get(0))){
                    returnMsg += "第"+index+"行:【客戶簡稱(必填)】列不能為空;";
                } else if(map.get(1)==null || "".equals(map.get(1))){
                    returnMsg += "第"+index+"行:【客戶全稱(必填)】列不能為空;";
                } else {
                    int num = 0;
                    QueryCustomParam params = new QueryCustomParam();
                    params.setShortName(map.get(0));
                    params.setCorpId(Long.valueOf(u.getCorpId()));
                    num = customService.checkCustom(params); //查詢相同客戶
                    
                    if(num==0){
                        Custom custom = new Custom();
                        custom.setId(UUIDUtil.getLongUUID());
                        custom.setShortName(map.get(0)==null? null : map.get(0));
                        custom.setName(map.get(1)==null? null : map.get(1));
                        custom.setNumber(map.get(2)==null? null : map.get(2));
                        custom.setAddress(map.get(3)==null? null : map.get(3));
                        custom.setUrl(map.get(4)==null? null : map.get(4));
                        custom.setDescription(map.get(5)==null? null : map.get(5));
                        custom.setCustomStatusId(map.get(6)==null? null : basedataService.getLabelId("custom_status", map.get(6), corpId) ); 
                        custom.setCustomLevelId(map.get(7)==null? null : basedataService.getLabelId("custom_level", map.get(7), corpId) );         
                        custom.setCreaterId(Long.valueOf(u.getUserId()));
                        custom.setCreateDate(date);
                        custom.setUpdaterId(Long.valueOf(u.getUserId()));
                        custom.setUpdateDate(date);
                        custom.setCorpId(Long.valueOf(u.getCorpId()));
                        
                        list_.add(custom);
                        
                    } else {
                        returnMsg += "第"+index+"行:【客戶簡稱(必填)】列:"+ map.get(0)+"已存在;";
                    }
                    index++;
                }
            }
            
            int cuccess = customService.batchInsert(list_); //批量導入客戶信息
            
            standardData.setReturnCode(0);
            standardData.setReturnData(null);
            
            error = count - success;
            standardData.setReturnMessage(returnMsg);
            
        } catch (Exception e) {
            log.error("批量導入客戶信息異常:" + e.getMessage());
            standardData.setReturnMessage(e.getMessage());
        }
        
        return JsonHelper.encodeObject2Json(standardData, "yyyy-MM-dd HH:mm:ss");
    }
    

 

讀取Excel內容工具類:

/**
     * 讀取Excel數據內容
     * @param InputStream
     * @return List<Map<String, String>>  Map的key是列Id(0代表第一列),值是具體內容
     */
    public List<Map<Integer, String>> readExcelContentByList(InputStream is) {
        
        List<Map<Integer, String>> list = new ArrayList<Map<Integer,String>>();
        
        try {
            //fs = new POIFSFileSystem(is);
            wb = new HSSFWorkbook(is);
            //wb = new XSSFWorkbook(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        sheet = wb.getSheetAt(0);
        
        // 得到總行數
        int rowNum = sheet.getLastRowNum();
        row = sheet.getRow(0);
        int colNum = row.getPhysicalNumberOfCells();
        
        // 正文內容應該從第二行開始,第一行為表頭的標題
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            int j = 0;
            Map<Integer,String> map = new HashMap<Integer, String>();
            
            while (j < colNum) {
                // 每個單元格的數據內容用"-"分割開,以后需要時用String類的replace()方法還原數據
                // 也可以將每個單元格的數據設置到一個javabean的屬性中,此時需要新建一個javabean
                // str += getStringCellValue(row.getCell((short) j)).trim() +
                // "-";
                
                map.put(j, getCellFormatValue(row.getCell((short) j)).trim().replaceAll("\t\r", ""));
                //str += getCellFormatValue(row.getCell((short) j)).trim() + "    ";
                j++;
            }
            list.add(map);
        }
        return list;
    }
    

 


免責聲明!

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



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