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

Java读取Excel文件内容的简单实例

程序员文章站 2023-12-20 12:20:40
借助于apathe的,由于上传文件不支持.jar所以请下载后将文件改为.jar,在应用程序中添加poi.jar包,并将需要读取的excel文件放入根目录即可 本例使用ja...

借助于apathe的,由于上传文件不支持.jar所以请下载后将文件改为.jar,在应用程序中添加poi.jar包,并将需要读取的excel文件放入根目录即可

本例使用java来读取excel的内容并展出出结果,代码如下:

复制代码 代码如下:

import java.io.bufferedinputstream;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.text.decimalformat;
import java.text.simpledateformat;
import java.util.arraylist;
import java.util.arrays;
import java.util.date;
import java.util.list;

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 exceloperate {

    public static void main(string[] args) throws exception {
       file file = new file("exceldemo.xls");
       string[][] result = getdata(file, 1);
       int rowlength = result.length;
       for(int i=0;i<rowlength;i++) {
           for(int j=0;j<result[i].length;j++) {
              system.out.print(result[i][j]+"\t\t");
           }
           system.out.println();
       }

    }
    /**
     * 读取excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行
     * @param file 读取数据的源excel
     * @param ignorerows 读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1
     * @return 读出的excel中数据的内容
     * @throws filenotfoundexception
     * @throws ioexception
     */
    public static string[][] getdata(file file, int ignorerows)
           throws filenotfoundexception, ioexception {
       list<string[]> result = new arraylist<string[]>();
       int rowsize = 0;
       bufferedinputstream in = new bufferedinputstream(new fileinputstream(
              file));
       // 打开hssfworkbook
       poifsfilesystem fs = new poifsfilesystem(in);
       hssfworkbook wb = new hssfworkbook(fs);
       hssfcell cell = null;
       for (int sheetindex = 0; sheetindex < wb.getnumberofsheets(); sheetindex++) {
           hssfsheet st = wb.getsheetat(sheetindex);
           // 第一行为标题,不取
           for (int rowindex = ignorerows; rowindex <= st.getlastrownum(); rowindex++) {
              hssfrow row = st.getrow(rowindex);
              if (row == null) {
                  continue;
              }
              int temprowsize = row.getlastcellnum() + 1;
              if (temprowsize > rowsize) {
                  rowsize = temprowsize;
              }
              string[] values = new string[rowsize];
              arrays.fill(values, "");
              boolean hasvalue = false;
              for (short columnindex = 0; columnindex <= row.getlastcellnum(); columnindex++) {
                  string value = "";
                  cell = row.getcell(columnindex);
                  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 = "";
                     }
                  }
                  if (columnindex == 0 && value.trim().equals("")) {
                     break;
                  }
                  values[columnindex] = righttrim(value);
                  hasvalue = true;
              }

              if (hasvalue) {
                  result.add(values);
              }
           }
       }
       in.close();
       string[][] returnarray = new string[result.size()][rowsize];
       for (int i = 0; i < returnarray.length; i++) {
           returnarray[i] = (string[]) result.get(i);
       }
       return returnarray;
    }

    /**
     * 去掉字符串右边的空格
     * @param str 要处理的字符串
     * @return 处理后的字符串
     */
     public static string righttrim(string str) {
       if (str == null) {
           return "";
       }
       int length = str.length();
       for (int i = length - 1; i >= 0; i--) {
           if (str.charat(i) != 0x20) {
              break;
           }
           length--;
       }
       return str.substring(0, length);
    }
}

上一篇:

下一篇: