`
砺雪凝霜
  • 浏览: 152198 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

读取Excel表格中数据的方法

阅读更多

1.读取字符串 :

    cell.toString

2.读取Excel表格中的电话号码(数字):

        DecimalFormat df = new DecimalFormat("#");
        String responsiblemenPhone = df.format(c4 .getNumericCellValue());

3.读取date类型
  if (0 == c4.getCellType()) {
       if (HSSFDateUtil.isCellDateFormatted(c4)) {
        Date d = c4.getDateCellValue();
        createTime = new Timestamp(d.getTime());
   } 

常量说明取值
Cell.CELL_TYPE_NUMERIC 数值类型 cell.getNumericCellValue()
或cell.getDateCellValue()
Cell.CELL_TYPE_STRING 字符串类型 cell.getStringCellValue()
或cell.toString()
Cell.CELL_TYPE_BOOLEAN 布尔类型 cell.getBooleanCellValue()
Cell.CELL_TYPE_FORMULA 表达式类型 cell.getCellFormula()
Cell.CELL_TYPE_ERROR 异常类型
不知道何时算异常
cell.getErrorCellValue()
Cell.CELL_TYPE_BLANK 空,不知道何时算空 空就不要取值了吧

下面是一个Excel导入的demo:

public String saveSuccessfulCaseByExcel(SysUser u, File file,
   String fileFileName) {
  String path;
  FileInputStream is = null;
  StringBuffer newFileName = new StringBuffer("");
  int index = StringUtils.lastIndexOf(fileFileName, '.');
  HashSet<OmpServiceSuccessfulCase> set = new HashSet<OmpServiceSuccessfulCase>();
  Boolean flag1 = false;
  Boolean flag2 = false;
  Boolean flag3 = false;
  Boolean flag4 = false;
  String extFileName = StringUtils.substring(fileFileName, index + 1);
  System.out.println(fileFileName);
  // 修改上传的文件名开始
  newFileName = new StringBuffer();
  String time = new SimpleDateFormat("yyyyMMddHHmmssSSS")
    .format(new Date());
  newFileName.append(time);
  for (int i = 0; i < 3; i++) {
   newFileName.append(new Random().nextInt(10));
  }
  // 修改上传的文件名结束
  String separator = java.io.File.separator; // 分隔符
  path = Platform.getInstance().getRealPath() + separator + "file"
    + separator + newFileName.append(u.getOrgId()) + "."
    + extFileName;// 设置保存路径
  File destFile = new File(path);
  try {
   FileUtils.copyFile(file, destFile);
  } catch (IOException e2) {
   // TODO Auto-generated catch block
   e2.printStackTrace();
  }
  File excelFile = new File(path);
  try {
   is = new FileInputStream(excelFile);
  } catch (FileNotFoundException e2) {
   // TODO Auto-generated catch block
   e2.printStackTrace();
  }
  System.out.println(is);
  Workbook workbook = null;
  try {
   workbook = WorkbookFactory.create(is);
  } catch (InvalidFormatException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  Sheet sheet = workbook.getSheetAt(0);// 默认读取的是第一个sheet
  // 检查模板格式是否正确
  Row row1 = sheet.getRow(0);
  int count = row1.getPhysicalNumberOfCells();
  Cell cc1 = row1.getCell(0);
  Cell cc2 = row1.getCell(1);
  Cell cc3 = row1.getCell(2);
  Cell cc4 = row1.getCell(3);
  if (count == 4 && "服务ID(服务ID一定要是该账号发布的服务ID)".equals(cc1.toString())
    && "标题(40个字以内)".equals(cc2.toString())
    && "成功案例详情(2000字以内)".equals(cc3.toString())
    && "创建时间(yyyy/MM/dd)".equals(cc4.toString())) {
   System.out.println(cc4.toString());
   System.out.println("总共:" + sheet.getPhysicalNumberOfRows());
   // 基本校验开始
   if (sheet.getPhysicalNumberOfRows() <= 1) {
    return "导入数据不能为空!";
   } else if (sheet.getPhysicalNumberOfRows() > 1) {
    // 进行迭代
    for (int i = sheet.getFirstRowNum() + 1; i < sheet
      .getPhysicalNumberOfRows(); i++) {
     int k = i + 1;
     Row row = sheet.getRow(i);
     Cell c1 = row.getCell(0);// ompBelowService.serviceId
     Cell c2 = row.getCell(1);// ompBelowService.belowServiceIncome
     Cell c3 = row.getCell(2);
     Cell c4 = row.getCell(3);
     OmpServiceSuccessfulCase ossfc = new OmpServiceSuccessfulCase();
     if (c1 != null && c2 != null && c3 != null && c4 != null) {
      String sid = c1.toString().trim();
      String title = c2.toString().trim();
      String detail = c3.toString().trim();
      Timestamp createTime = null;
      if (sid.length() != 32) {
       flag1 = false;
       return "第" + k + "行服务ID必须为32位";
      } else {
       flag1 = true;
      }
      if (title.length() > 40) {
       flag2 = false;
       return "第" + k + "行成功案例标题必须在40字以内";
      } else {
       flag2 = true;
      }

      if (detail.length() > 2000) {
       flag3 = false;
       return "第" + k + "行成功案例详情必须在2000字以内";
      } else {
       flag3 = true;
      }
      if (0 == c4.getCellType()) {
       if (HSSFDateUtil.isCellDateFormatted(c4)) {
        Date d = c4.getDateCellValue();
        createTime = new Timestamp(d.getTime());
        flag4 = true;
       }
      } else {
       flag4 = false;
       return "第" + k + "行日期格式不对";
      }

      if (flag1 && flag2 && flag3 && flag4) {
       ossfc.setServiceId(sid);
       ossfc.setCaseName(title);
       ossfc.setCaseDetail(detail);
       ossfc.setCreateTime(createTime);
       set.add(ossfc);
      }
     }
    }
    // 基本校验结束,数据库校验开始
    // 校验服务是否存在
    for (OmpServiceSuccessfulCase e : set) {
     String serivceId = e.getServiceId();
     String caseName = e.getCaseName();
     String caseDetail = e.getCaseDetail();
     Timestamp createTime = e.getCreateTime();
     OmpService os = (OmpService) baseTransaction.get(
       OmpService.class, serivceId);
     if (os == null) {
      return "导入的服务ID不存在!";
     } else if (!os.getOrgId().equalsIgnoreCase(u.getOrgId())
       && "1".equals(os.getIfDel())) {
      return "您没有发布服务ID所对应的服务!";
     } else {
      // 校验数据库中是否存在相同的成功案例
      e.setCreateTime(createTime);
      System.out.println(createTime.toString());
      e.setServiceCode(os.getServiceCode());
      e.setServiceId(os.getId());
      e.setServiceName(os.getServiceName());
      e.setCreateuserId(u.getOrgId());
      e.setCreateuserName(u.getUsername());
      e.setOrgId(os.getOrgId());
      e.setOrgName(os.getOrgName());
      e.setOrgType(os.getOrgType());
      e.setCaseName(caseName);
      e.setCaseDetail(caseDetail.replaceAll(
        "(^\\s{1,})|(\\s{1,}$)", ""));
      e.setIfDel("1");
      e.setLastOperatorId(u.getId());
      e
        .setLastOperatAction("saveSuccessfulCaseByExcel.action");
      CommonOrganization co = (CommonOrganization) baseTransaction
        .get(CommonOrganization.class, u.getOrgId());
      CommonWindow cw = (CommonWindow) baseTransaction.get(
        CommonWindow.class, u.getOrgId());
      if (co == null) {
       e.setOwnWin("ompompompompompompompompompomp60");
      } else {
       e.setOwnWin(co.getOwnWin());
      }
      baseTransaction.save(e);
      return null;
     }
    }
   }
  } else {
   return "请按照模板进行数据导入!";
  }
  return null;
 }
}

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics