前端导入excel, Java后台解析

1.接收逻辑
  @PostMapping("/importsXls")
  public String importsXls(@RequestParam(value = "multipartfile", required = false )
   MultipartFile multipartfile){
    File file = null;
    InputStream ins = null;
    ins = multipartfile.getInputStream();
    file = new File(multipartfile.getOriginalFilename());
    inputStreamToFile(ins, file);
    String s = this.getContent(file.toString(), 0, isok, 0);
  }
2.MultipartFile转File
  private static void inputStreamToFile(InputStream ins, File file) {
   try {
   OutputStream os = new FileOutputStream(file);
   int bytesRead = 0;
   byte[] buffer = new byte[8192];
   while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
   os.write(buffer, 0, bytesRead);
   }
   os.close();
   ins.close();
   } catch (Exception e) {
   e.printStackTrace();
   }
  }
3.解析excel
  public static String getContent(String file, int page, int i, int j) {
   String s = null;
  try {
   //解析
   org.apache.poi.ss.usermodel.Workbook workbook = null;
   //文件后缀
   String extString = file.substring(file.lastIndexOf("."));
   InputStream is = new FileInputStream(file);
  if (".xls".equals(extString)) {
   workbook = new HSSFWorkbook(is);
   Sheet sheet = workbook.getSheetAt(page); //选择sheet页
   HSSFRow row = (HSSFRow) sheet.getRow(i);
   //读取string类型
   row.getCell(j).setCellType(1);
   HSSFCell data = row.getCell(j);
   s = String.valueOf(data);
   if (s.lastIndexOf(".0") != -1) {
   s = s.substring(0, s.indexOf("."));
   }
   } else if (".xlsx".equals(extString)) {
   workbook = new XSSFWorkbook(is);
   Sheet sheet = workbook.getSheetAt(page); //选择sheet页
   XSSFRow row = (XSSFRow) sheet.getRow(i);
   //读取string类型
   row.getCell(j).setCellType(1);
   XSSFCell data = row.getCell(j);
   s = String.valueOf(data);
   } else {
   return "文件格式不符!";
   }
   } catch (Exception e) {
   e.printStackTrace();
   }
   return s;
  }

注:以上内容仅供个人学习记录使用,如有问题,请慎用!
 
 

posted @ 2021-02-19 15:44  夏天丷  阅读(643)  评论(0编辑  收藏  举报