本人在學習使用java的過程當中,須要驗證一下excel表格裏面的數據是否與數據庫中的數據相等。因爲數據太多,故想着用java讀取excel數據再去數據庫驗證。上網看了一下資料本身寫了一個讀取excel文檔的方法,驗證數據庫的方法暫時還沒寫,自娛自樂,只能抽時間了。如今把讀取excel的方法分享出來。java
//讀取excel文檔,除第一行爲標題外內容爲數字 public static List<List<Map<String, String>>> readExcel(File filepath) throws Exception{ /*首先判斷文件是否存在 * 在判斷文件類型,xls仍是xlsx */ if (!filepath.exists()) { output("文件不存在!"); } String filename = filepath.toString();//轉化爲string類型 String fileType = filename.substring(filename.lastIndexOf(".") + 1, filename.length());//提取文件名後綴 InputStream is = null; Workbook wb = null; try { is = new FileInputStream(filepath); if (fileType.equals("xls")) { wb = new HSSFWorkbook(is); } else if (fileType.equals("xlsx")) { wb = new XSSFWorkbook(is); } else { output("文件名錯誤!"); } //新建集合,考慮到要用value值去查詢數據庫,因此value設置爲string類型 List<List<Map<String, String>>> result = new ArrayList<List<Map<String,String>>>(); int sheetSize = wb.getNumberOfSheets();//獲取表格的個數 for (int i = 0; i < sheetSize; i++) {//遍歷全部表格 Sheet sheet = wb.getSheetAt(i); List<Map<String, String>> sheetList = new ArrayList<Map<String, String>>(); List<String> titles = new ArrayList<String>();//放置全部的標題 int rowSize = sheet.getLastRowNum() + 1;//此處getLastRowNum()方法獲取的行數從0開始,故要+1 for (int j = 0; j < rowSize; j++) {//遍歷全部行 Row row = sheet.getRow(j); if (row == null) {//略過空行 continue; } int cellSize = row.getLastCellNum();//獲取列數 if (j == 0) {//第一行是標題行 for (int k = 0; k < cellSize; k++) {//添加到標題集合中 Cell cell = row.getCell(k); titles.add(cell.toString()); } } else {//其餘行是數據行,爲數字 Map<String, String> rowMap = new HashMap<String, String>();//保存一行的數據 for (int k = 0; k < titles.size(); k++) {//遍歷保存此行數據 Cell cell = row.getCell(k); String key = titles.get(k); String value = null; if (cell != null) { /*這裏由於讀取excel數據默認值是double類型的,但個人數據都是整數,爲了方便先進行一次轉換 * 先判斷數據類型,而後先轉換而後在複製給value * 數值類型是0,字符串類型是1,公式型是2,空值是3,布爾值4,錯誤5 */ if (row.getCell(k).getCellType() == 0) { value =(int) row.getCell(k).getNumericCellValue()+""; }else { value = cell.toString();//轉換成string賦值給value } } rowMap.put(key, value);//把數據存入map集合 } sheetList.add(rowMap);//把存好行的數據存入表格的集合中 } } result.add(sheetList);//把表格的數據存到excel的集合中 } return result; } catch (FileNotFoundException e) { throw e; } finally { if (is != null) { is.close(); } } }
方法的思路是從網上看來的,中間把代碼敲了一遍,發現不少地方不太對,不知道是否是由於年份久遠的緣由。這個方法我作了一些本身的優化,輸入參數那個地方我改爲了file類型,判斷了一下文件是否存在。在讀取行數據的時候先轉換了一下格式。中文的註釋,我也本身從新寫了一遍。但願能對你有所幫助。git