1. 程式人生 > >java利用poi讀取excel中資料

java利用poi讀取excel中資料

所需的jar包:


程式碼:

/**
	 *
	 * @param cell
	 *            一個單元格的物件
	 * @return 返回該單元格相應的型別的值
	 */
	public static Object getRightTypeCell(Cell cell) {
		Object object = null;
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_STRING: {
			object = cell.getStringCellValue();
			break;
		}
		case Cell.CELL_TYPE_NUMERIC: {
			if (HSSFDateUtil.isCellDateFormatted(cell)) {// 處理日期格式、時間格式
				SimpleDateFormat sdf = null;
				if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
						.getBuiltinFormat("h:mm")) {
					sdf = new SimpleDateFormat("HH:mm");
				} else {// 日期
					sdf = new SimpleDateFormat("yyyy-MM-dd");
				}
				Date date = cell.getDateCellValue();
				object = sdf.format(date);
			} else {
				object = cell.getNumericCellValue();
			}
			break;
		}
		case Cell.CELL_TYPE_FORMULA: {
			cell.setCellType(Cell.CELL_TYPE_NUMERIC);
			object = cell.getNumericCellValue();
			break;
		}
		case Cell.CELL_TYPE_BLANK: {
			object = cell.getStringCellValue();
			break;
		}
		}
		return object;
	}

	/**
	 * 讀取出filePath中的所有資料資訊
	 * 
	 * @param filePath
	 *            excel檔案的絕對路徑
	 * 
	 */
	@SuppressWarnings("deprecation")
	public static void getDataFromExcel(String filePath) {
		// 判斷是否為excel型別檔案
		if (!filePath.endsWith(".xls") && !filePath.endsWith(".xlsx")) {
			System.out.println("檔案不是excel型別");
		}
		FileInputStream fis = null;
		Workbook wookbook = null;
		int flag = 0;
		try {
			// 獲取一個絕對地址的流
			fis = new FileInputStream(filePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			// 2003版本的excel,用.xls結尾
			wookbook = new HSSFWorkbook(fis);// 得到工作簿
		} catch (Exception ex) {
			try {
				// 2007版本的excel,用.xlsx結尾
				wookbook = new XSSFWorkbook(filePath);// 得到工作簿
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// 得到一個工作表
		Sheet sheet = wookbook.getSheetAt(0);
		// 獲得表頭
		Row rowHead = sheet.getRow(0);
		// 根據不同的data放置不同的表頭
		Map<Object, Integer> headMap = new HashMap<Object, Integer>();
		try {
			// ----------------這裡根據你的表格有多少列
			while (flag < rowHead.getPhysicalNumberOfCells()) {
				Cell cell = rowHead.getCell(flag);
				if (getRightTypeCell(cell).toString().equals("學號")) {
					headMap.put("id", flag);
				}
				if (getRightTypeCell(cell).toString().equals("姓名")) {
					headMap.put("name", flag);
				}
				if (getRightTypeCell(cell).toString().equals("生日")) {
					headMap.put("date", flag);
				}
				flag++;
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("表頭不合規範,請修改後重新匯入");
		}
		// 獲得資料的總行數
		int totalRowNum = sheet.getLastRowNum();

		if (0 == totalRowNum) {
			System.out.println("Excel內沒有資料!");
		}
		Cell cell_1 = null, cell_2 = null, cell_3 = null;
		// 獲得所有資料
		for (int i = 1; i <= totalRowNum; i++) {
			// 獲得第i行物件
			Row row = sheet.getRow(i);
			try {
				cell_1 = row.getCell(headMap.get("id"));
				cell_2 = row.getCell(headMap.get("name"));
				cell_3 = row.getCell(headMap.get("date"));
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("獲取單元格錯誤");
			}
			try {
				double temp = (Double) getRightTypeCell(cell_1);
				int id = (int) temp;
				String name = (String) getRightTypeCell(cell_2);
				String date = (String) getRightTypeCell(cell_3);
				System.out.println("id:" + id + " name:" + name + " date:"
						+ date);
			} catch (ClassCastException e) {
				e.printStackTrace();
				System.out.println("資料不全是數字或全部是文字!");
			}
		}
	}

	public static void main(String[] args) {
		getDataFromExcel("F:" + File.separator + "test.xlsx");
	}