当前位置: 移动技术网 > IT编程>开发语言>Java > Java用POI解析excel并获取所有单元格数据的实例

Java用POI解析excel并获取所有单元格数据的实例

2019年07月19日  | 移动技术网IT编程  | 我要评论

1.导入poi相关jar包

org.apache.poi jar

2.代码示例

public list getallexcel(file file, string tablename, string fname,
  string enterpriseid, string reportid, string projectid)
  throws filenotfoundexception, ioexception, classnotfoundexception,
  instantiationexception, illegalaccessexception,
  nosuchmethodexception, securityexception, illegalargumentexception,
  invocationtargetexception, parseexception {


  list listt = new arraylist();

  try {
    fileinputstream fis = new fileinputstream(file);
    workbook workbook = null;
    if (fname.tolowercase().endswith("xlsx")) {
      workbook = new xssfworkbook(fis);
    } else if (fname.tolowercase().endswith("xls")) {
      workbook = new hssfworkbook(new poifsfilesystem(fis));
    }
    int numberofsheets = workbook.getnumberofsheets();

    for (int i = 0; i < numberofsheets; i++) {
      sheet sheet = workbook.getsheetat(i);
      for (int j = 1; j < sheet.getphysicalnumberofrows(); j++) { // 获取每行
        xssfrow row = (xssfrow) sheet.getrow(j);
        if(row!=null){
          list list = new arraylist();
          for (int k = 0; k < sheet.getrow(0).getphysicalnumberofcells(); k++) { // 获取每个单元格
            cell cell = row.getcell(k);
            if (cell == null) {
              list.add("");
              continue;
            }
            switch (cell.getcelltype()) {
            case cell.cell_type_string:
              list.add(cell.getrichstringcellvalue().getstring());
              break;
            case cell.cell_type_numeric:
              if (dateutil.iscelldateformatted(cell)) {
                list.add(cell.getdatecellvalue());
              } else {
                list.add(cell.getnumericcellvalue());
              }
              break;
            case cell.cell_type_boolean:
              list.add(cell.getbooleancellvalue());
              break;
            case cell.cell_type_formula:
              list.add(cell.getcellformula());
              break;
            default:
              list.add("");
            break;
          }
        }

        listt.add(getbyreflect(tablename, list, enterpriseid,reportid, projectid));
      }
    }
  }
    fis.close();
      } catch (ioexception e) {
        e.printstacktrace();
      }
    return listt;
}

以上这篇java用poi解析excel并获取所有单元格数据的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网