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

java使用poi读取excel内容方法实例

程序员文章站 2024-02-14 16:44:10
复制代码 代码如下:import java.io.bufferedinputstream;import java.io.file;import java.io.filein...

复制代码 代码如下:

import java.io.bufferedinputstream;
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.nio.channels.filechannel;
import java.text.decimalformat;
import java.text.simpledateformat;
import java.util.date;

import org.apache.poi.hssf.usermodel.hssfcell;
import org.apache.poi.hssf.usermodel.hssfdateutil;
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.poifs.filesystem.poifsfilesystem;

public class fileoperator {
   public static void main(string[] args) throws exception {
      string path = "f:\\1.xls";
   print(path);
     }

  public static void print(string path) throws ioexception{
      bufferedinputstream in = new bufferedinputstream(
     new fileinputstream(new file(path)));
   poifsfilesystem fs = new poifsfilesystem(in);
   hssfworkbook wb = new hssfworkbook(fs);
   hssfcell cell = null;
   hssfsheet st = wb.getsheetat(0);
   for (int rowindex = 0; rowindex <= st.getlastrownum(); rowindex++) {
    hssfrow row = st.getrow(rowindex);
    if (row == null) {
     continue;
    }
    for (short columnindex = 0, size = row.getlastcellnum(); columnindex <= size; columnindex++) {
     cell = row.getcell(columnindex);
     string value = "";
     if (cell != null) {
      // 注意:一定要设成这个,否则可能会出现乱码
      cell.setencoding(hssfcell.encoding_utf_16);
      switch (cell.getcelltype()) {
      case hssfcell.cell_type_string:
       value = cell.getstringcellvalue();
       break;
      case hssfcell.cell_type_numeric:
       if (hssfdateutil.iscelldateformatted(cell)) {
        date date = cell.getdatecellvalue();
        if (date != null) {
         value = new simpledateformat("yyyy-mm-dd")
           .format(date);
        } else {
         value = "";
        }
       } else {
        value = new decimalformat("0").format(cell
          .getnumericcellvalue());
       }
       break;
      case hssfcell.cell_type_formula:
       // 导入时如果为公式生成的数据则无值
       if (!cell.getstringcellvalue().equals("")) {
        value = cell.getstringcellvalue();
       } else {
        value = cell.getnumericcellvalue() + "";
       }
       break;
      case hssfcell.cell_type_blank:
       break;
      case hssfcell.cell_type_error:
       value = "";
       break;
      case hssfcell.cell_type_boolean:
       value = (cell.getbooleancellvalue() == true ? "y"
         : "n");
       break;
      default:
       value = "";
      }
      system.out.println(rowindex + "," + columnindex + ":"
        + value);
     }
     if (columnindex == 0 && value.trim().equals("")) {
      break;
     }
    }
   }
     }

}