使用poi框架读取excel文件

来源:互联网 发布:闰年判断方法 c语言 编辑:程序博客网 时间:2024/06/05 19:28
一,Java读写Excel的包是Apache POI(项目地址:http://poi.apache.org/)
Apache POI 代码例子地址:http://poi.apache.org/spreadsheet/quick-guide.html
本例子可以读取Microsoft Office Excel 2003/2007/2010,具体代码及注释如下:
读取“.xls”格式使用  import org.apache.poi.hssf.usermodel.*;包的内容,例如:HSSFWorkbook
读取“.xlsx”格式使用 import org.apache.poi.xssf.usermodel.*; 包的内容,例如:XSSFWorkbook
读取两种格式使用    import org.apache.poi.ss.usermodel.*    包的内容,例如:Workbook

Poi包里有4个主要的类,包括:
Workbook------工作表,通过WorkbookFactory的create(FileInputStream fis)方法获取,
Sheet------------表格,Workbook实例的getSheetAt(int num)方法获取,
Row--------------行,Sheet实例的getRow(int num)方法获取,
Cell--------------单元格,Row实例的getCell(int num)方法获取,
最后通过Cell实例根据数据类型调用对应的方法获取单元格的值。

excel文件内容:包含字符串、日期、数值、公式等数值类型.

二,具体代码
事例代码(一):
import org.apache.poi.ss.usermodel.Cell;  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.ss.usermodel.WorkbookFactory;  import org.apache.poi.ss.usermodel.DateUtil;  /**  * 读取Excel测试,兼容 Excel 2003/2007/2010  */  public String readExcel()  {  SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");  try {  //同时支持Excel 2003、2007  File excelFile = new File("/home/zht/test.xls"); //创建文件对象  FileInputStream is = new FileInputStream(excelFile); //文件流  Workbook workbook = WorkbookFactory.create(is); //这种方式 Excel 2003/2007/2010 都是可以处理的  int sheetCount = workbook.getNumberOfSheets();  //Sheet的数量  //遍历每个Sheet  for (int s = 0; s < sheetCount; s++) {  Sheet sheet = workbook.getSheetAt(s);  int rowCount = sheet.getPhysicalNumberOfRows(); //获取总行数  //遍历每一行  for (int r = 0; r < rowCount; r++) {  Row row = sheet.getRow(r);  int cellCount = row.getPhysicalNumberOfCells(); //获取总列数  //遍历每一列  for (int c = 0; c < cellCount; c++) {  Cell cell = row.getCell(c);  int cellType = cell.getCellType();  String cellValue = null;  switch(cellType) {  case Cell.CELL_TYPE_STRING: //文本  cellValue = cell.getStringCellValue();  break;  case Cell.CELL_TYPE_NUMERIC: //数字、日期  if(DateUtil.isCellDateFormatted(cell)) {  cellValue = fmt.format(cell.getDateCellValue()); //日期型  }  else {  cellValue = String.valueOf(cell.getNumericCellValue()); //数字  }  break;  case Cell.CELL_TYPE_BOOLEAN: //布尔型  cellValue = String.valueOf(cell.getBooleanCellValue());  break;  case Cell.CELL_TYPE_BLANK: //空白  cellValue = cell.getStringCellValue();  break;  case Cell.CELL_TYPE_ERROR: //错误  cellValue = "错误";  break;  case Cell.CELL_TYPE_FORMULA: //公式  cellValue = "错误";  break;  default:  cellValue = "错误";  }  System.out.print(cellValue + "    ");  }  System.out.println();  }  }    }  catch (Exception e) {  e.printStackTrace();  }    return Action.SUCCESS;  }

事例代码二:
public class Poi {  private Sheet sheet;    //表格类实例  LinkedList[] result;    //保存每个单元格的数据 ,使用的是一种链表数组的结构    //读取excel文件,创建表格实例  private void loadExcel(String filePath) {  FileInputStream inStream = null;  try {  inStream = new FileInputStream(new File(filePath));  Workbook workBook = WorkbookFactory.create(inStream);   sheet = workBook.getSheetAt(0);           } catch (Exception e) {  e.printStackTrace();  }finally{  try {  if(inStream!=null){  inStream.close();  }                  } catch (IOException e) {                  e.printStackTrace();  }  }  }  //获取单元格的值  private String getCellValue(Cell cell) {  String cellValue = "";  DataFormatter formatter = new DataFormatter();  if (cell != null) {  //判断单元格数据的类型,不同类型调用不同的方法  switch (cell.getCellType()) {  //数值类型  case Cell.CELL_TYPE_NUMERIC:  //进一步判断 ,单元格格式是日期格式   if (DateUtil.isCellDateFormatted(cell)) {  cellValue = formatter.formatCellValue(cell);  } else {  //数值  double value = cell.getNumericCellValue();  int intValue = (int) value;  cellValue = value - intValue == 0 ? String.valueOf(intValue) : String.valueOf(value);  }  break;  case Cell.CELL_TYPE_STRING:  cellValue = cell.getStringCellValue();  break;  case Cell.CELL_TYPE_BOOLEAN:  cellValue = String.valueOf(cell.getBooleanCellValue());  break;  //判断单元格是公式格式,需要做一种特殊处理来得到相应的值  case Cell.CELL_TYPE_FORMULA:{  try{  cellValue = String.valueOf(cell.getNumericCellValue());  }catch(IllegalStateException e){  cellValue = String.valueOf(cell.getRichStringCellValue());  }    }  break;  case Cell.CELL_TYPE_BLANK:  cellValue = "";  break;  case Cell.CELL_TYPE_ERROR:  cellValue = "";  break;  default:  cellValue = cell.toString().trim();  break;  }  }  return cellValue.trim();  }        //初始化表格中的每一行,并得到每一个单元格的值  public  void init(){  int rowNum = sheet.getLastRowNum() + 1;  result = new LinkedList[rowNum];  for(int i=0;i<rowNum;i++){  Row row = sheet.getRow(i);  //每有新的一行,创建一个新的LinkedList对象  result[i] = new LinkedList();  for(int j=0;j<row.getLastCellNum();j++){  Cell cell = row.getCell(j);  //获取单元格的值  String str = getCellValue(cell);  //将得到的值放入链表中  result[i].add(str);  }  }  }  //控制台打印保存的表格数据  public void show(){  for(int i=0;i<result.length;i++){  for(int j=0;j<result[i].size();j++){  System.out.print(result[i].get(j) + "\t");  }  System.out.println();  }  }  public static void main(String[] args) {  Poi poi = new Poi();  poi.loadExcel("jxl.xls");  poi.init();  poi.show();  }    }  

备注:上述的代码只能解析xls格式 的文件,对于xlsx格式则需要另外几个类解析,XSSFWorkbook、XSSFSheet、XSSFRow、XSSFCell,其实方法和思路是一样,相应的改改类名而已,不是很复杂。

三,poi解析excel中数据类型对应的值

Cell.CELL_TYPE_STRING: 1 文本

Cell.CELL_TYPE_NUMERIC: 0 数字,日期

Cell.CELL_TYPE_BOOLEAN: 4 布尔型

Cell.CELL_TYPE_BLANK: 3 空白

Cell.CELL_TYPE_ERROR: 5 空白

Cell.CELL_TYPE_FORMULA: 2 公式




0 0