当前位置: 移动技术网 > IT编程>开发语言>Java > Java使用poi包读取Excel文档代码分享

Java使用poi包读取Excel文档代码分享

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

项目需要解析excel文档获取数据,就在网上找了一些资料,结合自己这次使用,写下心得:

1、maven项目需加入如下依赖:

<dependency>
    <groupid>org.apache.poi</groupid>
    <artifactid>poi</artifactid>
    <version>3.10-final</version>
  </dependency>
  <dependency>
    <groupid>org.apache.poi</groupid>
    <artifactid>poi-ooxml</artifactid>
    <version>3.10-final</version>
  </dependency>

直接上测试类,类里有完善的注释:

package shindo.java;

import java.io.fileinputstream;
import java.io.inputstream;
import java.util.arraylist;
import java.util.list;

import org.apache.poi.hssf.usermodel.hssfcell;
import org.apache.poi.hssf.usermodel.hssfrow;
import org.apache.poi.hssf.usermodel.hssfsheet;
import org.apache.poi.hssf.usermodel.hssfworkbook;
import org.apache.poi.ss.usermodel.cell;
import org.apache.poi.xssf.usermodel.xssfcell;
import org.apache.poi.xssf.usermodel.xssfrow;
import org.apache.poi.xssf.usermodel.xssfsheet;
import org.apache.poi.xssf.usermodel.xssfworkbook;

public class excelutil {

  public static void main(string[] args) {
    string path = "d:\\ide\\workspace-neon\\java\\src\\refund.xls";
    try {
      list<list<string>> result = new excelutil().readxls(path);
      system.out.println(result.size());
      for (int i = 0; i < result.size(); i++) {
        list<string> model = result.get(i);
        system.out.println("ordernum:" + model.get(0) + "--> orderamount:" + model.get(1));
      }

    } catch (exception e) {
      e.printstacktrace();
    }
  }

  /**
   * 
  * @title: readxls 
  * @description: 处理xls文件
  * @param @param path
  * @param @return
  * @param @throws exception  设定文件 
  * @return list<list<string>>  返回类型 
  * @throws
  * 
  * 从代码不难发现其处理逻辑:
  * 1.先用inputstream获取excel文件的io流
  * 2.然后穿件一个内存中的excel文件hssfworkbook类型对象,这个对象表示了整个excel文件。
  * 3.对这个excel文件的每页做循环处理
  * 4.对每页中每行做循环处理
  * 5.对每行中的每个单元格做处理,获取这个单元格的值
  * 6.把这行的结果添加到一个list数组中
  * 7.把每行的结果添加到最后的总结果中
  * 8.解析完以后就获取了一个list<list<string>>类型的对象了
  * 
   */
  private list<list<string>> readxls(string path) throws exception {
    inputstream is = new fileinputstream(path);
    // hssfworkbook 标识整个excel
    hssfworkbook hssfworkbook = new hssfworkbook(is);
    list<list<string>> result = new arraylist<list<string>>();
    int size = hssfworkbook.getnumberofsheets();
    // 循环每一页,并处理当前循环页
    for (int numsheet = 0; numsheet < size; numsheet++) {
      // hssfsheet 标识某一页
      hssfsheet hssfsheet = hssfworkbook.getsheetat(numsheet);
      if (hssfsheet == null) {
        continue;
      }
      // 处理当前页,循环读取每一行
      for (int rownum = 1; rownum <= hssfsheet.getlastrownum(); rownum++) {
        // hssfrow表示行
        hssfrow hssfrow = hssfsheet.getrow(rownum);
        int mincolix = hssfrow.getfirstcellnum();
        int maxcolix = hssfrow.getlastcellnum();
        list<string> rowlist = new arraylist<string>();
        // 遍历改行,获取处理每个cell元素
        for (int colix = mincolix; colix < maxcolix; colix++) {
          // hssfcell 表示单元格
          hssfcell cell = hssfrow.getcell(colix);
          if (cell == null) {
            continue;
          }
          rowlist.add(getstringval(cell));
        }
        result.add(rowlist);
      }
    }
    return result;
  }

  /**
   * 
  * @title: readxlsx 
  * @description: 处理xlsx文件
  * @param @param path
  * @param @return
  * @param @throws exception  设定文件 
  * @return list<list<string>>  返回类型 
  * @throws
   */
  private list<list<string>> readxlsx(string path) throws exception {
    inputstream is = new fileinputstream(path);
    xssfworkbook xssfworkbook = new xssfworkbook(is);
    list<list<string>> result = new arraylist<list<string>>();
    // 循环每一页,并处理当前循环页
    for (xssfsheet xssfsheet : xssfworkbook) {
      if (xssfsheet == null) {
        continue;
      }
      // 处理当前页,循环读取每一行
      for (int rownum = 1; rownum <= xssfsheet.getlastrownum(); rownum++) {
        xssfrow xssfrow = xssfsheet.getrow(rownum);
        int mincolix = xssfrow.getfirstcellnum();
        int maxcolix = xssfrow.getlastcellnum();
        list<string> rowlist = new arraylist<string>();
        for (int colix = mincolix; colix < maxcolix; colix++) {
          xssfcell cell = xssfrow.getcell(colix);
          if (cell == null) {
            continue;
          }
          rowlist.add(cell.tostring());
        }
        result.add(rowlist);
      }
    }
    return result;
  }

  // 存在的问题
  /*
   * 其实有时候我们希望得到的数据就是excel中的数据,可是最后发现结果不理想
   * 如果你的excel中的数据是数字,你会发现java中对应的变成了科学计数法。
   * 所以在获取值的时候就要做一些特殊处理来保证得到自己想要的结果
   * 网上的做法是对于数值型的数据格式化,获取自己想要的结果。
   * 下面提供另外一种方法,在此之前,我们先看一下poi中对于tostring()方法:
   * 
   * 该方法是poi的方法,从源码中我们可以发现,该处理流程是:
   * 1.获取单元格的类型
   * 2.根据类型格式化数据并输出。这样就产生了很多不是我们想要的
   * 故对这个方法做一个改造。
   */
  /*public string tostring(){
    switch(getcelltype()){
      case cell_type_blank:
        return "";
      case cell_type_boolean:
        return getbooleancellvalue() ? "true" : "false";
      case cell_type_error:
        return erroreval.gettext(geterrorcellvalue());
      case cell_type_formula: 
        return getcellformula();
      case cell_type_numeric:
        if(dateutil.iscelldateformatted(this)){
          dateformat sdf = new simpledateformat("dd-mmm-yyyy")
          return sdf.format(getdatecellvalue());
        }
        return getnumericcellvalue() + "";
      case cell_type_string: 
        return getrichstringcellvalue().tostring();
      default :
        return "unknown cell type:" + getcelltype();
    }
  }*/

  /**
   * 改造poi默认的tostring()方法如下
  * @title: getstringval 
  * @description: 1.对于不熟悉的类型,或者为空则返回""控制串
  *        2.如果是数字,则修改单元格类型为string,然后返回string,这样就保证数字不被格式化了
  * @param @param cell
  * @param @return  设定文件 
  * @return string  返回类型 
  * @throws
   */
  public static string getstringval(hssfcell cell) {
    switch (cell.getcelltype()) {
    case cell.cell_type_boolean:
      return cell.getbooleancellvalue() ? "true" : "false";
    case cell.cell_type_formula:
      return cell.getcellformula();
    case cell.cell_type_numeric:
      cell.setcelltype(cell.cell_type_string);
      return cell.getstringcellvalue();
    case cell.cell_type_string:
      return cell.getstringcellvalue();
    default:
      return "";
    }
  }
}

总结

以上就是本文关于java使用poi包读取excel文档代码分享的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

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

相关文章:

验证码:
移动技术网