package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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;

/**
 * 解析excel2007
 */
public class ReadExcel2007 {

	private XSSFWorkbook workbook;

	public ReadExcel2007(File excelFile)throws FileNotFoundException, IOException {
		workbook = new XSSFWorkbook(new FileInputStream(excelFile));
	}

	/**
	 *读取所有列
	 */
	public List<List> getDatasInSheetarrall(int sheetNumber)
			throws FileNotFoundException, IOException {
		List result = new ArrayList();

		//获得指定的表
		XSSFSheet sheet = workbook.getSheetAt(sheetNumber);
		//获得数据总行数
		int rowCount = sheet.getLastRowNum();
		if (rowCount < 1) {
			return result;
		}
		//逐行读取数据
		for (int rowIndex = 0; rowIndex <= rowCount; rowIndex++) {
			//获得行对象
			XSSFRow row = sheet.getRow(rowIndex);
			if (row != null) {
				List list = new ArrayList();
				int columnCount = row.getLastCellNum();
				//读取所有的列	
				for (int i = 0; i < columnCount; i++) {
					//获得本行中单元格的个数
					//获得本行中各单元格中的数据
					XSSFCell cell = row.getCell(Short.parseShort(i + ""));
					//获得指定单元格中数据
					Object cellStr = this.getCellString(cell);
					if (null != cellStr) {
						list.add(cellStr.toString().trim());
					} else {
						list.add("");
					}
				}
				result.add(list);
			}
		}
		return result;
	}

	/**
	 * 获得单元格中的内容
	 * @param cell
	 * @return
	 */
	protected Object getCellString(XSSFCell cell) {
		Object result = null;
		if (cell != null) {
			int cellType = cell.getCellType();
			switch (cellType) {
			case XSSFCell.CELL_TYPE_STRING:
				result = cell.getStringCellValue();
				break;
			case XSSFCell.CELL_TYPE_NUMERIC:
				result = cell.getNumericCellValue();
				break;
			case XSSFCell.CELL_TYPE_FORMULA:
				result = cell.getNumericCellValue();
				break;
			case XSSFCell.CELL_TYPE_ERROR:
				break;
			case XSSFCell.CELL_TYPE_BOOLEAN:
				result = cell.getBooleanCellValue();
				break;
			case XSSFCell.CELL_TYPE_BLANK:
				result = null;
				break;
			}
		}
		return result;
	}

	public static void main(String[] args) throws Exception {
		File file = new File("C:\\Users\\Administrator\\Desktop\\金钥匙\\测试清单.xlsx");
		ReadExcel2007 parser3 = new ReadExcel2007(file);
		List<List> datas = parser3.getDatasInSheetarrall(0);
		for (int i = 0; i < datas.size(); i++) {
			List listinfo = (List) datas.get(i);
			for (int j = 0; j < listinfo.size(); j++) {
				System.out.print(listinfo.get(j) + "				");
			}
			System.out.println("");
		}
		//XMLEventFactory
		//C:\java\MyEclipse 6.0\myeclipse\eclipse\plugins\com.genuitec.eclipse.j2eedt.core_6.0.0.zmyeclipse60020070820\data\libraryset\EE_5
	}

}
