java POI 读取EXCEL文件

来源:互联网 发布:php文件下载 编辑:程序博客网 时间:2024/04/30 15:54

*强调内容*从POI官网http://poi.apache.org/download.html下载最新的jar包将其解压到文件夹,将下列jar包导入工程lib文件:

新建测试excel文件:user.xls,user.xlsx其内容:

工程内容:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
 * Poi读Excel
 * 
 * @author yuanzi
 * 
 */
public class PoiReadDemo
{
   public static void main(String[] args)
   {
  pareExc("user.xls");
   }
private static void pareExc(String path) {
  File xlsFile = new File(path);
  //获取 文件后缀
  String str=path.substring(path.lastIndexOf(".")+1);
 // System.out.println(str);
  Workbook wb = null;
  try {
  if(str.equals("xls")){
  //获取2003版本xls的Workbook 
wb = new HSSFWorkbook(new FileInputStream(xlsFile));
  }else if(str.equals("xlsx")){
//获取2007版本xlsx的Workbook 
  wb=new XSSFWorkbook(xlsFile);
  }
  //获取表格Sheet
  Sheet sheet=wb.getSheetAt(0);
  //s.getLastRowNum()总行数
  for(int row=0;row<=sheet.getLastRowNum();row++){
 //获取每一行Row的数据
  Row r=sheet.getRow(row);
 for(int cell=0;cell<r.getLastCellNum();cell++ ){
 //获取每一格的数据cell
 Cell c=r.getCell(cell);
 printexcel(c); 
 }
 System.out.println();
  }
  } catch (InvalidFormatException e) {
e.printStackTrace();
  }catch (FileNotFoundException e) {
e.printStackTrace();
  } catch (IOException e) {
e.printStackTrace();
  } 
}
   private static void printexcel(Cell c){
  //获取每一格的数据类型
  CellType cp=c.getCellTypeEnum();
 if(CellType.NUMERIC.equals(cp)){
 System.out.print(c.getNumericCellValue()+"\t");
 }else if(CellType.STRING.equals(cp)){
 System.out.print(c.getStringCellValue()+" \t");
 }
   }
}

运行结果:

新手上路大家多多指教!具体代码demo下载地址:http://download.csdn.net/download/ly549826/10115321