通用版本的 excel 表格

 03版本用 HSSFWorkbook  03以上的版本用 XSSFWorkbook 

      import org.apache.poi.hssf.usermodel.HSSFCell;
      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.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.xssf.usermodel.XSSFCell;
      import org.apache.poi.xssf.usermodel.XSSFRow;
      import org.apache.poi.xssf.usermodel.XSSFSheet;
      import org.apache.poi.xssf.usermodel.XSSFWorkbook;
      import org.junit.Test;

    /**
	 * 读所有版本的 excel 表格
	 * @throws IOException 
	 */
	@Test
	public void readExcel() throws IOException{
		boolean is03Excel ;
		String fileName = "D:\\src\\itcastTax\\tmp.xlsx";
		//excel 03 和 07 以上版本 的正则表达式   ^$ 是开头和结束
		String regex = "^.+\\.(?i)((xls)|(xlsx))$";
		//判断是否为excel文件
		if(fileName.matches(regex)){
			is03Excel = fileName.matches("^. + \\.(?i)((xls))$");
			FileInputStream read = new FileInputStream(fileName);
			//是03版本的就用HSSFWorkbook 反之用 XSSFWorkbook 
			Workbook wookbook = is03Excel ? new HSSFWorkbook(read) : new XSSFWorkbook(read);
			Sheet sheet = wookbook.getSheet("sheet1");
			Row row = sheet.getRow(0);
			Cell cell = row.getCell(0);
			System.out.println(cell.getStringCellValue());
			wookbook.close();
			read.close();
		}
	}

  

posted @ 2017-06-12 10:50  苦海无涯、苦尽甘来  阅读(382)  评论(0编辑  收藏  举报