Springboot poi 導入、導出excel 簡單步驟

一、導入excel:

首先來個區分2003 與2007 版的工具類

public class ExcelImportUtils
{
  // @描述:是否是2003的excel,返回true是2003   
  public static boolean isExcel2003(String filePath)  {    
      return filePath.matches("^.+\\.(?i)(xls)$");    
  }    
   
  //@描述:是否是2007的excel,返回true是2007   
  public static boolean isExcel2007(String filePath)  {    
      return filePath.matches("^.+\\.(?i)(xlsx)$");    
  }    
    
  /** 
   * 驗證EXCEL文件 
   * @param filePath 
   * @return 
   */  
  public static boolean validateExcel(String filePath){  
      if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))){    
          return false;    
      }    
      return true;  
  }  
}

后臺代碼

controller層

/**
     * 導入會員信息
     * @param file
     * @return
     */
    @RequestMapping("importExcel")
    @ResponseBody
    public Object importExcel(@RequestParam(value="filename") MultipartFile file){
      if(file.isEmpty()){  
        return ResponseUtil.fail(403, "文件為空!");
      } 
      InputStream is = null;
      try
      {
        is = file.getInputStream();
        //獲取文件名  
        String fileName = file.getOriginalFilename(); 
        
        //根據版本選擇創建Workbook的方式  
        Workbook wb = null;
        Sheet sheetAt = null;
        //根據文件名判斷文件是2003版本還是2007版本  
        if(ExcelImportUtils.isExcel2007(fileName)){  
           wb = new XSSFWorkbook(is);
           sheetAt = wb.getSheetAt(0);
        }else{  
           wb = new HSSFWorkbook(is);  
           sheetAt = wb.getSheetAt(0);
        }
        
        List<User> userlist = new ArrayList<User>();
        //用于密碼加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //用于生日轉換
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //double轉String
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        //false則不分組顯示數據, 如:999999999 
       //true則分組顯示數據,即每三位數為一個分組,分組間以英文半角逗號分隔, 如:999,999,999
        
        for (Row row : sheetAt) {
          int rowNum = row.getRowNum();
          if (rowNum == 0) {
              continue;
          }
          
          String name = row.getCell(0).getStringCellValue();//用戶名
          Double phone = row.getCell(1).getNumericCellValue();//手機號
          String sex = row.getCell(2).getStringCellValue();//性別
          String birthdayStr = row.getCell(3).getStringCellValue();//生日
          String level = row.getCell(4).getStringCellValue();//用戶等級
          
         /* 判斷格式
         String qty = "0";
          switch (row.getCell(1).getCellType()) {
              case HSSFCell.CELL_TYPE_STRING:
                    qty = row.getCell(1).getRichStringCellValue().getString().trim();
                    break;
              case HSSFCell.CELL_TYPE_NUMERIC:
                    qty = nf.format(row.getCell(1).getNumericCellValue());
                    break;
              default:
                    qty = "";
                }
*/
          //判斷是否重復用戶名重復
          List<User> userList = userService.queryByUsername(name);
          if(!userList.isEmpty()){
            return ResponseUtil.fail(403, "該用戶名重復:"+ name);
          }
          
           //數據封裝 ,存到數據庫
          LitemallUser user = new LitemallUser();
          user.setUsername(name);
          user.setNickname(name);
          user.setGender(sex);
          user.setUserLevel(level);
          user.setAddTime(LocalDateTime.now());
          user.setStatus("可用");
          
          user.setMobile(nf.format(phone));
          user.setBirthday(LocalDate.parse(birthdayStr, df));
          user.setPassword(encoder.encode("123456"));
          
          userlist.add(user);
        }
        
       //保存數據到DB
        if(userlist.size()>0)
        userService.insertBatch(userlist);
      }
      catch (IOException e)
      {
        e.printStackTrace();
        return ResponseUtil.serious();
      }finally {
        if (is != null) {
          try {
              is.close();
          } catch (IOException e) {
              e.printStackTrace();
              return ResponseUtil.serious();
          }
        }
      }
      
      return ResponseUtil.ok();
    }

pom:

<!--導入Excel-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

最后是測試:

1536032496(1).jpg

使用Postman測試

Postman01.jpg
Postman02.jpg

這邊key要和controller 參數名對應
最后debug 可以獲取數據

二、導出excel:

簡單偽代碼:

/**
     * 條件導出用戶信息
     * @param response
     * @param user
     * @return
     */
    @RequestMapping("exportExcel")
    @ResponseBody
    public Object exportExcel(HttpServletResponse response,User user){
  
      //條件導出
      String level = user.getUserLevel();
      String status = user.getStatus();
      
      ServletOutputStream outputStream = null;
      HSSFWorkbook workbook = null;
      try {
          // 創建 excel 文件
          workbook = new HSSFWorkbook();
          // 創建一個標簽頁
          HSSFSheet sheet = workbook.createSheet("用戶信息");

          //設置列寬
          sheet.setColumnWidth(0, 3000);
          sheet.setColumnWidth(1, 3000);
          sheet.setColumnWidth(2, 3000);
          sheet.setColumnWidth(3, 3000);
          sheet.setColumnWidth(4, 3000);
          sheet.setColumnWidth(5, 3000);
          
          //創建格式
          HSSFCellStyle titleStyle = workbook.createCellStyle();
          titleStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
          titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        
          
          HSSFFont titleFont = workbook.createFont();
          titleFont.setBold(true);//粗體
          titleFont.setFontHeightInPoints((short)12);//大小
          titleFont.setFontName("宋體");//字體類型
          titleStyle.setFont(titleFont);
          
          // 創建標題行
          HSSFRow titleRow = sheet.createRow(0);
          
          HSSFCell cell0 = titleRow.createCell(0);
          cell0.setCellValue("用戶名");
          cell0.setCellStyle(titleStyle);
          
          HSSFCell cell1 = titleRow.createCell(1);
          cell1.setCellValue("手機號");
          cell1.setCellStyle(titleStyle);
          
          HSSFCell cell2 = titleRow.createCell(2);
          cell2.setCellValue("性別");
          cell2.setCellStyle(titleStyle);
          
          HSSFCell cell3 = titleRow.createCell(3);
          cell3.setCellValue("生日");
          cell3.setCellStyle(titleStyle);
          
          HSSFCell cell4 = titleRow.createCell(4);
          cell4.setCellValue("用戶等級");
          cell4.setCellStyle(titleStyle);
          
          HSSFCell cell5 = titleRow.createCell(5);
          cell5.setCellValue("狀態");
          cell5.setCellStyle(titleStyle);
          
         //DB查詢數據
         List<User> userList = userService.queryByLevelAndStatus(level, status);
         if(userList == null || userList.isEmpty()){
           return ResponseUtil.fail(403, "導出數據失敗,無用戶信息!");
         }
         
          
          // 封裝excel數據
          DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
          for (int i = 0; i < userList.size(); i++) {
              titleRow = sheet.createRow(i + 1);
              titleRow.createCell(0).setCellValue(userList.get(i).getUsername());
              titleRow.createCell(1).setCellValue(userList.get(i).getMobile());
              titleRow.createCell(2).setCellValue(userList.get(i).getGender());
              titleRow.createCell(4).setCellValue(userList.get(i).getUserLevel());
              titleRow.createCell(5).setCellValue(userList.get(i).getStatus());
              if(userList.get(i).getBirthday() !=null){
                titleRow.createCell(3).setCellValue(df.format(userList.get(i).getBirthday()));
              }
          }

          // 設置兩個頭 一個輸出流
          String filename = "會員信息.xls";
          outputStream = response.getOutputStream();
          // 響應信息,彈出文件下載窗口
          response.setContentType("APPLICATION/OCTET-STREAM");
          response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
          workbook.write(outputStream);
      } catch (Exception e) {
          e.printStackTrace();
          return ResponseUtil.fail(403, "導出數據失敗!" + e.getMessage());
      } finally {
          try {
              if (outputStream != null) {
                  workbook.close();
                  outputStream.close();
              }
          } catch (Exception e) {
              e.printStackTrace();
              return ResponseUtil.fail(403, "導出數據失敗!" + e.getMessage());
          }

      }
      return ResponseUtil.ok();
   }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,993評論 19 139
  • iOS網絡架構討論梳理整理中。。。 其實如果沒有APIManager這一層是沒法使用delegate的,畢竟多個單...
    yhtang閱讀 5,259評論 1 23
  • 哎呀呀 ,馬上就要面臨找工作了,媛媛心里緊張呀. 作為一個即將畢業的Android程序媛,開始面臨找工作了,...
    左神話閱讀 4,894評論 7 59
  • 轉自 1. 什么是Activity? 四大組件之一,一般的,一個用戶交互界面對應一個activity setCon...
    joe1632閱讀 1,422評論 0 7
  • 今天是時隔十幾年后我再一次踏進這家餛飩館,進去以后老板娘一個人在。老板娘看起來保養的很好,如今嫣然也是一美女...
    木子菲菲閱讀 479評論 4 0