1. 程式人生 > >基於Spring的Excel匯入匯出例項

基於Spring的Excel匯入匯出例項

Apache POI是建立和維護操作各種符合Office Open XML(OOXML)標準和微軟的OLE 2複合文件格式(OLE2)的Java API。用它可以使用Java讀取和建立,修改MS Excel檔案.而且,還可以使用Java讀取和建立MS Word和MSPowerPoint檔案。Apache POI 提供Java操作Excel解決方案。

正好專案中用到了這項技術,今天抽時間整理一下,以下進入正題:

1、jar包的引入,共用到了一下jar包


2、excel匯入的後臺程式碼

    /**
      * excel匯入
      * @param sql
      *
      */
     @RequestMapping(value="/upload",method = RequestMethod.POST)
     @ResponseBody   
     public PageResponse upload(@RequestParam("file")CommonsMultipartFile[] files,
                HttpServletRequest request,Model model, String sql){
           PageResponse page = new PageResponse();
           ArrayList<Economy> list = new ArrayList<Economy>();
           try {
                 InputStream is = files[0].getInputStream();//輸入流
                 POIFSFileSystem fs= new POIFSFileSystem(is);
                 HSSFWorkbook wb= new HSSFWorkbook(fs);
                 HSSFSheet sheet= wb.getSheetAt(0);
                 int lastRowNum = sheet.getLastRowNum();
                 ArrayList<String> sqllist  =new ArrayList<String>(); 

//迴圈拼sql語句             
                 for(int i=1;i<lastRowNum+1;i++){
                      HSSFRow row = sheet.getRow(i);
                     sql = "replace into info.etl_i_regiondata(province,county,years)values(";
                      HSSFCell cell = row.getCell(0);
                      sql+="'"+cell.getStringCellValue()+"',";
                      HSSFCell cell1 = row.getCell(1);
                      sql+="'"+cell1.getStringCellValue()+"',";
                      HSSFCell cell2 = row.getCell(2);
                      int cellValue2 = (int) cell2.getNumericCellValue();
                      sql+="'"+cellValue2+"',";
                  if(sql.endsWith(",")){
                       sql = sql.substring(0, sql.length()-1);
                  }
                  sql+=")";
                  sqllist.add(sql);
                }     
                 //System.out.println(JSONArray.fromObject(sqllist).toString());
                 JdbcUtil.executeSql(sql);//執行單條sql
                 JdbcUtil.executeSqlList(sqllist); //批量執行sql
                
                 page.setStatus(true);
                 page.setMessage("資料上傳成功");
           } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
           logger.error("資料匯入出錯:"+e.getMessage());
           page.setStatus(false);
                page.setMessage(e.getMessage());
           }
           return null;
     }

3、Excel根據查詢結果匯出後臺程式碼

    /**
      * excel匯出
      */
     @RequestMapping(value="/export")     
    public void export(HttpServletResponse response,ServletOutputStream outputStream,
    @RequestParam(value="city",required=false)String city,
    @RequestParam(value="county",required=false)String county,
    @RequestParam(value="years",required=false)String years){ 
           int MAN=Integer.valueOf(MAX);//設定最大匯出引數
           HashMap<String,Object> map = new HashMap<String,Object>();
           map.put("years", years);
           map.put("city",city);
           map.put("county", county);
           map.put("MAN", MAN);
        try{
           ArrayList<Economy> list = IEconomyService.findByExportMap(map);//獲取資料
             HSSFWorkbook workBook = new HSSFWorkbook(); 
             //在workbook中新增一個sheet,對應Excel檔案中的sheet 
              HSSFSheet sheet = workBook.createSheet("檔案"); 
              HSSFRow row = sheet.createRow(0);       
              HSSFCell cell = null; 
              String[] titles = { "省份", "縣", "年份"};               
              for (int i = 0; i < titles.length; i++){               
                  cell = row.createCell((i));
                  cell.setCellValue(titles[i]);
              } 
              // 構建表體資料 
              if (list != null && list.size() > 0) { 
                  for (int j = 0; j < list.size(); j++) 
                  { 
                      HSSFRow Row = sheet.createRow(j + 1);                  
                      Economy economy = list.get(j);                     
                      cell = Row.createCell(0);                 
                      cell.setCellValue(economy.getProvince());        
                      cell = Row.createCell(1);                  
                      cell.setCellValue(economy.getCounty());       
                      cell = Row.createCell(2);
                      int cellValue=Integer.valueOf(economy.getYears());
                      cell.setCellValue(cellValue);
                  } 
              } 
                  outputStream = response.getOutputStream();   
                   String fileName = URLEncoder.encode("檔案","UTF8");
                   response.setHeader("Content-disposition", "attachment; filename="+ fileName +".xls");// 組裝附件名稱和格式
                
                    workBook.write(outputStream); 
                    outputStream.flush(); 
                    outputStream.close(); 
             }catch(Exception e){
                e.printStackTrace();
                logger.error("Excel匯出資料出錯:"+e.getMessage());
             }
        }