欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-04-01 18:16:52
1.导入poi相关jar包 org.apache.poi jar 2.代码示例 public list getallexcel(file file, stri...

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并获取所有单元格数据的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。