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

一、導入excel:

首先來個區(qū)分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(); 
        
        //根據(jù)版本選擇創(chuàng)建Workbook的方式  
        Workbook wb = null;
        Sheet sheetAt = null;
        //根據(jù)文件名判斷文件是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();
        //用于生日轉(zhuǎn)換
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //double轉(zhuǎn)String
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        //false則不分組顯示數(shù)據(jù), 如:999999999 
       //true則分組顯示數(shù)據(jù)们衙,即每三位數(shù)為一個分組钾怔,分組間以英文半角逗號分隔, 如: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);
          }
          
           //數(shù)據(jù)封裝 ,存到數(shù)據(jù)庫
          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);
        }
        
       //保存數(shù)據(jù)到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 參數(shù)名對應
最后debug 可以獲取數(shù)據(jù)

二蒙挑、導出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 {
          // 創(chuàng)建 excel 文件
          workbook = new HSSFWorkbook();
          // 創(chuàng)建一個標簽頁
          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);
          
          //創(chuàng)建格式
          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);
          
          // 創(chuàng)建標題行
          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("狀態(tài)");
          cell5.setCellStyle(titleStyle);
          
         //DB查詢數(shù)據(jù)
         List<User> userList = userService.queryByLevelAndStatus(level, status);
         if(userList == null || userList.isEmpty()){
           return ResponseUtil.fail(403, "導出數(shù)據(jù)失敗宗侦,無用戶信息!");
         }
         
          
          // 封裝excel數(shù)據(jù)
          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, "導出數(shù)據(jù)失敺!" + e.getMessage());
      } finally {
          try {
              if (outputStream != null) {
                  workbook.close();
                  outputStream.close();
              }
          } catch (Exception e) {
              e.printStackTrace();
              return ResponseUtil.fail(403, "導出數(shù)據(jù)失敳鐾唷男旗!" + e.getMessage());
          }

      }
      return ResponseUtil.ok();
   }
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市欣鳖,隨后出現(xiàn)的幾起案子察皇,更是在濱河造成了極大的恐慌,老刑警劉巖泽台,帶你破解...
    沈念sama閱讀 221,635評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件让网,死亡現(xiàn)場離奇詭異,居然都是意外死亡师痕,警方通過查閱死者的電腦和手機溃睹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來胰坟,“玉大人因篇,你說我怎么就攤上這事泞辐。” “怎么了竞滓?”我有些...
    開封第一講書人閱讀 168,083評論 0 360
  • 文/不壞的土叔 我叫張陵咐吼,是天一觀的道長。 經(jīng)常有香客問我商佑,道長锯茄,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,640評論 1 296
  • 正文 為了忘掉前任茶没,我火速辦了婚禮肌幽,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘抓半。我一直安慰自己喂急,他們只是感情好,可當我...
    茶點故事閱讀 68,640評論 6 397
  • 文/花漫 我一把揭開白布笛求。 她就那樣靜靜地躺著廊移,像睡著了一般。 火紅的嫁衣襯著肌膚如雪探入。 梳的紋絲不亂的頭發(fā)上狡孔,一...
    開封第一講書人閱讀 52,262評論 1 308
  • 那天,我揣著相機與錄音蜂嗽,去河邊找鬼步氏。 笑死,一個胖子當著我的面吹牛徒爹,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播芋类,決...
    沈念sama閱讀 40,833評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼隆嗅,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了侯繁?” 一聲冷哼從身側(cè)響起胖喳,我...
    開封第一講書人閱讀 39,736評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎贮竟,沒想到半個月后丽焊,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,280評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡咕别,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,369評論 3 340
  • 正文 我和宋清朗相戀三年技健,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片惰拱。...
    茶點故事閱讀 40,503評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡雌贱,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情欣孤,我是刑警寧澤馋没,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站降传,受9級特大地震影響篷朵,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜婆排,卻給世界環(huán)境...
    茶點故事閱讀 41,870評論 3 333
  • 文/蒙蒙 一声旺、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧泽论,春花似錦艾少、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至鹦赎,卻和暖如春谍椅,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背古话。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評論 1 272
  • 我被黑心中介騙來泰國打工雏吭, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人陪踩。 一個月前我還...
    沈念sama閱讀 48,909評論 3 376
  • 正文 我出身青樓杖们,卻偏偏與公主長得像,于是被迫代替她去往敵國和親肩狂。 傳聞我的和親對象是個殘疾皇子摘完,可洞房花燭夜當晚...
    茶點故事閱讀 45,512評論 2 359

推薦閱讀更多精彩內(nèi)容

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